在模板参数中指定类方法 - 可选(默认参数)

时间:2011-12-25 21:19:07

标签: c++ templates

我想做这样的事情:

template <class T,class t_function = t::default_function>
class foo
{
   public:
   static void bar(T t)
   {
      t.t_function();
   }
};

class example1
{
   public:
       void default_function()
       {
           std::cout<<"test"<<std::endl;
       }
};

class example2
{
   public:
      void someotherfunction()
      {
         std::cout<<"test2"<<std::endl;
      }
};

//how to use it

foo<example1>::bar(example1()); //should work, since example1 has the default function

foo<example2,example2::someotherfunction>::bar(example2()); //should work too

用语言:我希望该函数的用户能够提供一种替代方法而不是默认方法。

我可以用C ++实现这个目标,如果是这样,怎么做?

1 个答案:

答案 0 :(得分:1)

也许是这样的:

template <class T, void(T::*TFun)() = &T::default_function>
struct Foo
{
    static void bar(T t)
    {
        (t.*TFun)();
    }
};

用法:

struct Zoo { void default_function() { } };
struct Zar { void bla() { } };

int main()
{
    Zoo z1;
    Zar z2;
    Foo<Zoo>::bar(z1);
    Foo<Zar, &Zar::bla>::bar(z2);
}