参见英文答案 >
How to pass a template function in a template argument list2个
对于我的生活,我无法让这个简单的奥术模板魔法工作:
对于我的生活,我无法让这个简单的奥术模板魔法工作:
- template<typename T,int a,int b>
- int f(T v){
- return v*a-b; // just do something for example
- }
- template<typename T,int b,template<typename,int,int> class func>
- class C{
- int f(){
- return func<T,a,b>(3);
- }
- };
- int main(){
- C<float,3,2,f> c;
- }
这可能不涉及仿函数吗?
解决方法
f应该是一个类 – 你有一个功能.
见下文:
- // Class acts like a function - also known as functor.
- template<typename T,int b>
- class f
- {
- int operator()(T v)
- {
- return v*a-b; // just do something for example
- }
- };
- template<typename T,int> class func>
- class C
- {
- int f()
- {
- return func<T,b>(3);
- }
- };
- int main()
- {
- C<float,f> c;
- }
…如果需要移植遗留代码,请使用改编版本(将函数调整为类模板):
- #include <iostream>
- template<typename T,int b>
- int f(T v)
- {
- std::cout << "Called" << std::endl;
- return v*a-b; // just do something for example
- }
- template<typename T,int> class func>
- struct C
- {
- int f()
- {
- return func<T,b>(3);
- }
- };
- template <class T,int b>
- struct FuncAdapt
- {
- T x_;
- template <class U>
- FuncAdapt( U x )
- : x_( x )
- {}
- operator int() const
- {
- return f<T,b>( x_ );
- }
- };
- int main()
- {
- C<float,FuncAdapt > c;
- c.f();
- }