类外的成员模板函数定义无法生成Visual studio 2013

Member template function definition outside class fails to build Visual studio 2013

本文关键字:Visual 2013 studio 定义 成员 函数      更新时间:2023-10-16

我已经粘贴到了我正在处理的一段复杂模板代码的最底层。

 1  template <typename T>
 2  class Base
 3      : public T
 4  {
 5  public:
 6      template <typename W, W& (T::ToImpl::*Func)()>
 7      bool Foo();
 8  };
 9  
10  template <typename T>
11  template <typename W, W& (T::ToImpl::*Func)()>
12  bool Base<T>::Foo()
13  {}
14  
15  int
16  main()
17  {
18      return 0;
19  }

代码非常直接,所以我不做任何解释。我无法使用Visual Studio 2013(又名VC++12)编译此代码。它给出以下错误:

main.cc(13): error C2244: 'Base<T>::Foo' : unable to match function definition to an existing declaration
          definition
          'bool Base<T>::Foo(W)'
          existing declarations
          'bool Base<T>::Foo(W)'

出于好奇,我尝试用g++(4.4.7)编译上面的代码,它编译得很好。

如果有人能解释为什么代码无法在windows上编译,我将不胜感激?修复会更甜蜜。:)

这应该有效:

template <typename T>
struct to_impl
{
    typedef typename T::ToImpl type;
};
template <typename T>
class Base
    : public T
{
public:
    template <typename W, W& (to_impl<T>::type::*Func)()>
    bool Foo();
};
template <typename T>
template <typename W, W& (to_impl<T>::type::*Func)()>
bool Base<T>::Foo()
{
}

尽管在Base:中实现Foo会更容易

template <typename T>
class Base
    : public T
{
public:
    template <typename W, W& (T::ToImpl::*Func)()>
    bool Foo()
    {
    }
};