0

我無法將模板方法的定義放在類之外。考慮下面的代碼來自.h文件(剝離了非必要的代碼來理解這個問題):C++模板方法定義在類中不匹配

template <typename T> class CStyleAllocator 
{ 
public: 
    // Conversion constructor declaration 
    template <typename U> CStyleAllocator(const CStyleAllocator<U>&); 
}; 

// Attempted definition 
template <typename T, typename U> CStyleAllocator<T>::CStyleAllocator(
    typename const CStyleAllocator<U>& 
) 
{ 
} 

在Visual C++ 2010編譯器輸出這樣的錯誤:

1>c:\dev\devworkspaces\dev.main\platform\cpp\memory\cstyleallocator.h(67): error C2244: 'CStyleAllocator<T>::{ctor}' : unable to match function definition to an existing declaration 
1>   definition 
1>   'CStyleAllocator<T>::CStyleAllocator(const CStyleAllocator<U> &)' 
1>   existing declarations 
1>   'CStyleAllocator<T>::CStyleAllocator(const CStyleAllocator<U> &)' 
1>   'CStyleAllocator<T>::CStyleAllocator(void)' 

我試圖定義一個依賴於2個泛型類型的轉換構造函數。

合併的聲明和定義中的類的工作:

template <typename T> class CStyleAllocator 
{ 
public: 
    template <typename U> CStyleAllocator(const CStyleAllocator<U>&) { } 
}; 

你看到我在做什麼錯?

回答

0

試試這樣說:

template <typename T> 
template<typename U> 
CStyleAllocator<T>::CStyleAllocator(
    const CStyleAllocator<U>& 
) 
{ 
} 
+0

它的工作原理,謝謝! – GDICommander