2015-02-11 83 views
0

我粘貼了我正在處理的複雜模板代碼片段的最小值。成員模板外部類的函數定義無法構建Visual Studio 2013

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上編譯?修復會更加甜美。 :)

+0

什麼是'ToImpl'? – Axalo 2015-02-11 00:36:03

+0

@Axalo它將是模板類中定義的類型。類似這樣的 - class base { public: typedef SomeClass ToImpl; } – slowstart 2015-02-11 00:43:04

回答

1

這應該工作:

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() 
{ 
} 

雖然它會更容易實現FooBase

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

謝謝@Axalo!我正準備發佈內聯修復錯誤。這會幫助我瞭解非內聯修復程序的工作方式。你介意解釋你的修復嗎?再次感謝您的回覆。 – slowstart 2015-02-11 01:00:49

+0

爲什麼它在內聯定義時起作用?你還沒有告訴編譯器T :: ToImpl是一個類型。 @Axalo – slowstart 2015-02-11 01:38:27

+0

@slowstart是的你是對的。真奇怪... – Axalo 2015-02-11 01:48:46