错误C2893:无法专门化函数模板VC ++ 2012

时间:2013-12-02 06:44:29

标签: c++ templates overloading

鉴于此代码,我遇到编译错误,我遇到了问题:

struct TestType
{
  void PrintX( void )
  {
    printf( "TestType::PrintX : %d\n", x );
  }

  int x;
};

// Error here, BuildFunction overload not found
Function f = BuildFunction<decltype( &TestType::PrintX ), &TestType::PrintX>( &TestType::PrintX );

// Here is the overload
template <typename FunctionType, FunctionType *FunctionPtr, typename C>
Function BuildFunction( void (C::*fn)( void ) )
{
  return Function( fn, &CallMethodVoid<FunctionType, FunctionPtr, C> );
}

我的确切错误信息是:

1>main.cpp(141): error C2893: Failed to specialize function
  template 'Function BuildFunction(void (__thiscall C::* )(void))'
1>          With the following template arguments:
1>          'void (__thiscall TestType::* )(void)'
1>          'TestType'

这段代码适用于静态C函数(以及适当的重载),我在尝试处理类或结构方法时遇到了这个问题。关于问题可能是什么想法?

1 个答案:

答案 0 :(得分:3)

问题在于BuildFunction<>的第二个模板参数的类型。

第一个模板参数FunctionType,由于您已将void (TestType::*)(void)作为第一个模板参数传递,因此推导为decltype(&TestType::PrintX)。您指定的第二个模板参数读取FunctionType *。所以第二个模板参数期望void (TestType::**)(void)(指向成员函数的指针),我认为这不是你想要的。如果您将第二个模板参数更改为FunctionType而不是FunctionType *,我认为您会得到您期望的结果。

相关问题