2015-04-23 74 views
0

我正在寻找一种将函数和类方法绑定到特定原型的方法。使用模板将类方法绑定到特定的原型

比方说,我要绑定的功能和类方法与这个原型

int (float) 

这一个

void() 

这里是我的代码

class Toto 
{ 
public: 
    int test(float f) { std::cout << "Toto::test " << f << std::endl; return 0; } 
} toto; 

int test(float f) 
{ 
    std::cout << "test " << f << std::endl; 
    return 0; 
} 

template <typename T, T t> 
void func() 
{ 
    t(4.0f); 
} 

template <typename T> 
void func<int (T::*)(float), int (T::*method)(float)>() 
{ 
    toto::*method(5.0f); 
} 

auto main(int, char**) -> int 
{ 
    func<int(*)(float), &test>(); 
    func<void (Toto::*)(float), &Toto::test>(); 

return EXIT_SUCCESS; 

}

钍e函数绑定工作正常,但方法之一似乎有一些我不明白的语法问题。 g ++给我这个错误:

src/main.cpp:28:6: error: parse error in template argument list 
src/main.cpp:28:55: error: function template partial specialization ‘func<int (T::*)(float), <expression error> >’ is not allowed 

任何想法?

+0

你不能偏专攻模板函数。 – Jarod42

+0

'auto main(int,char **) - > int' - 来吧,真的......? –

回答

1

你不能偏专攻模板的功能,但你可以为类/结构:

namespace details 
{ 
    template <typename T, T t> 
    struct func_impl 
    { 
     void operator()() const { t(4.0f); } 
    }; 

    template <typename T, int (T::*method)(float)> 
    struct func_impl<int (T::*)(float), method> 
    { 
     void operator()() const { (toto.*method)(5.0f); } 
    }; 

} 

template <typename T, T t> 
void func() 
{ 
    details::func_impl<T, t>{}(); 
} 

Live demo

相关问题