有没有办法调用operator()( int )类模板的仿函数,Foo如下所示(在线版本)
template<typename T>
struct Foo
{
template<typename U>
void operator()( int )
{
}
};
int main(int argc, char *argv[])
{
Foo<char> foo;
foo<bool>( 42 );
}
Run Code Online (Sandbox Code Playgroud)
我在gcc 4.9.3中收到错误消息
error: expected primary-expression before ‘bool’
foo<bool>( 42 );
Run Code Online (Sandbox Code Playgroud)
我会在前面加上仿用template,如果成员函数是不是一个函子,并与被前缀::,.或->.没有一些帮助,编译器就不知道如何解析这个表达式; 作为仿函数或类型的匿名对象的实例化foo<int>.
它会起作用;
foo.operator()<bool>( 42 );
Run Code Online (Sandbox Code Playgroud)
运算符最适合使用推导出的模板参数类型.
您没有提供使用它的上下文的足够细节,作为您可以考虑的替代方案;
U作为参数例如;
template<typename U>
void operator()( int, U&& /*initial*/ )
{
// use the initial value of U
}
// called as...
foo(42, true); // U is bool in your example
Run Code Online (Sandbox Code Playgroud)
或者只是成员函数;
template<typename U>
void my_func( int )
{
}
// called as...
foo.my_fun<bool>( 42 );
Run Code Online (Sandbox Code Playgroud)