2010-07-13 68 views
2

我有以下的(最小化)的代碼,這在VC2005的工作,但在2010年VS2010 C++成員模板函數的專業化錯誤

template <typename TDataType> 
class TSpecWrapper 
    { 
    public: 
    typedef typename TDataType::parent_type index_type; 


    public: 

    template <bool THasTriangles> 
    void Spec(index_type& io_index) 
     { std::cout << "False version" << std::endl; } 

    template <> 
    void Spec<true>(index_type& io_index) 
     { std::cout << "True version" << std::endl; } 
    }; 

似乎不再起作用,當「INDEX_TYPE」是一個依賴型,我總是得到一個C2770:專門化的無效顯式模板參數(s)錯誤。請注意,這段代碼實際上足以產生錯誤 - 一個空的main就足以編譯它,模板甚至不需要實例化。

它工作正常,如果index_type不是依賴類型。任何想法,爲什麼在VC2010中如此,如果這實際上是標準行爲或錯誤,並且我能解決它?

+0

你所傳遞的'TDataType'參數類型? – 2010-07-13 10:30:30

+2

有一個'index_type'和'index'參數,是一個錯字嗎? – 2010-07-13 10:50:18

+1

[非命名空間範圍中的顯式特化]的可能的重複(http://stackoverflow.com/questions/3052579/explicit-specialization-in-non-namespace-scope) – 2010-07-13 11:06:01

回答

7

解決方法

template <bool v> struct Bool2Type { static const bool value = v; }; 

template <typename TDataType> 
class TSpecWrapper 
{ 
public: 
    typedef typename TDataType::parent_type index_type; 


public: 
    template <bool THasTriangles> 
    void Spec(index_type& io_index) 
    { 
     return SpecHelp(io_index, Bool2Type<THasTriangles>()); 
    } 

private: 
    void SpecHelp(index_type& io_index, Bool2Type<false>) 
    { std::cout << "False version" << std::endl; } 

    void SpecHelp(index_type& io_index, Bool2Type<true>) 
    { std::cout << "True version" << std::endl; } 

}; 
+0

謝謝你的這 - 幫助我解決問題! – 2010-07-13 11:42:05

+0

這是一個*非常*有用的解決方法! – Vargas 2010-10-05 18:00:28

4

這是根據C++標準14.7.3/18:

在一個顯式特聲明一類模板的成員或成員的模板,在命名空間範圍中,構件模板和一些出現 其封閉的類模板可能保持未被專門化, ,除非聲明不明確專門化類成員模板,如果它的封閉類 模板沒有明確專用以及。 < ...>

不允許專門Spec沒有專門TDataType

+0

但是,如果index_type不是依賴類型(例如int),它工作正常...... – 2010-07-13 11:32:15

+0

實際上,通過閱讀回覆,看起來VS2005非常自由,2010年稍微不太自由,但仍然更加自由比標準允許。所以我想在某種程度上這個問題是一個重複的http://stackoverflow.com/questions/3052579/explicit-specialization-in-non-namespace-scope(至少該問題的答案也包括我的) – 2010-07-13 11:44:01