Top/article/Make-friendly-templates
English | Japanese
English | Japanese

Menu

  • Top
  • Akihiko Yamaguchi 山口 明彦
  • Project プロジェクト
  • Text テキスト
  • Recent articles 最近の記事
  • Articles 記事一覧 (a to z)
  • Search 検索

Tags タグ †

  • [c++][bash][python][latex][php]
  • [linux][windows][mac][android]
  • [math][algorithm][idea][trick]
  • [liboctave][opencv][git][ros]
  • [setting][bug][general]
↑

Recent articles 最近の記事 †

2019-07-02
  • article/Display-Unix-Time
  • article/Synchronize-Linux-Time-to-Remote
2018-09-27
  • article/python-multimode-singleton
2018-09-02
  • article/rosinstall-git-default-remote
2017-07-28
  • article/SubMenu
2017-03-05
  • article/Import-a-different-version-of-OpenCV-in-Python
2015-08-17
  • article/DRC-finals-2015
2015-01-05
  • article/Upgrade-Android-to-Lollipop
2015-01-01
  • article/Kernel-panic-of-Linux-when-using-Xtion
  • article/Do-not-skip-freeing-data-when-using-tri-mesh-in-ODE
Access: 1/1759 - Admin

Make friendly templates

template な friend

[c++]
2011-12-07

テンプレートクラスや関数を friend にする方法のメモ.危険性についても言及.

方法 †

こんな感じで書く:

class TTest
{
  ...
  template<typename T> friend void Func(TTest &test,const T &x);
}

サンプル:

#include <iostream>

class TTest
{
public:
  TTest() : x(-1) {}
  const int& X() const {return x;}
private:
  int x;
  template<typename T> friend void Func(TTest &test,const T &x);
};

template<typename T> void Func(TTest &test,const T &x)
{
  test.x= x;
}

using namespace std;
#define print(var) std::cout<<#var"= "<<(var)<<std::endl
int main(int argc, char**argv)
{
  TTest test;
  print(test.X());
  Func(test,3.14);
  print(test.X());
  return 0;
}

結果:

test.X()= -1
test.X()= 3
↑

危険性 †

しかし,通常の friend 関数やクラスと比べて,テンプレート関数やクラスを friend にすると危険性が増す. つまり,ユーザが friend 関数やクラスを特殊化したものを定義できる可能性がある. 例えば,上のコードに,ユーザは

template<> void Func(TTest &test,const int &x)
{
  test.x= 100000;
}

という特殊化を(悪意を持って)追加できる.




Last-modified:2015-01-01 (Thu) 09:29:08 (3833d)
Site admin: Akihiko Yamaguchi.
Written by: Akihiko Yamaguchi.
System: PukiWiki 1.5.0. PHP 5.2.17. HTML conversion time: 0.008 sec.