2011-12-25 113 views
-1

我想做些事情是这样的:指定类方法模板参数 - 可选(默认参数)

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++中实现吗?如果是这样,怎么办?

+0

已经是-1,没有任何解释。悲伤的脸 :( – TravisG 2011-12-25 21:24:07

回答

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); 
}