2017-04-06 195 views
2

这里的东西,它似乎很可能通过一个模板化的结构里面包含一些静态函数是这样的:如何将模板函数作为模板类参数传递?

template <class T> struct FunctionHolder {}; 

template <> struct FunctionHolder<string> { 
    static void f(const string &s) { 
     cout << "f call " << s << endl; 
    } 
}; 

template <class Key, class Value, class Holder = FunctionHolder<Key>> 
class Foo { 
    public: 
    Foo(Key k) { 
     Holder::f(k); 
    } 
}; 

int main(int argc, char *argv[]) { 
    Foo<string, int> foo = Foo<string, int>("test_string"); 
} 

但是,才有可能通过直接模板化的功能,而不会被静态定义的模板化的结构?我已经试过这一点,它不会编译:

template <class string> static void f(const string &s) { 
    cout << "f call " << k << endl; 
} 

template <class Key, class Value, typename func<Key>> class Foo { 
    public: 
    Foo(Key k) { 
     func(k); 
    } 
}; 

int main(int argc, char *argv[]) { 
    Foo<string, int> foo = Foo<string, int>("test_string"); 
} 

问这个因为这一切的不冷静而被迫创建虚拟结构(含一堆静态功能结构)用作模板类型为主类。

+0

为什么不'FUNC ''在构造函数Foo'?提供用例。 – Yakk

回答

1

不幸的是,功能模板不能用作template template arguments;您可以使用函数指针作为非类型模板参数,例如

template <class Key, class Value, void(*func)(const Key&) = f<Key>> class Foo { 
    public: 
    Foo(Key k) { 
     func(k); 
    } 
}; 

LIVE

+0

@BPL对不起,我无法访问你张贴的网址(我的网络不好);我尝试了一个演示[在这里](http://rextester.com/EYJTKA4322)。 – songyuanyao

+0

@BPL只需更改参数名称;不要使用'int'。 http://rextester.com/FGQB33074 – songyuanyao

相关问题