在类模板中调用模板化仿函数

Olu*_*ide 7 c++ templates

有没有办法调用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>.

101*_*010 5

是的,但它很难看:

foo.operator()<bool>( 42 );
Run Code Online (Sandbox Code Playgroud)


Nia*_*all 5

它会起作用;

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)