2015-04-23 86 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

相關問題