2015-06-15 29 views
1

在以下示例中,我有一個定義引用類的對象類。兩者都接受可變性作爲模板參數。在'obj'是'Const'的情況下,我想禁止'Non_Const'類型的引用。該示例在Visual C++ 2012中生成模糊消息「編譯器中發生了內部錯誤」。是否應編譯?如果沒有,爲什麼,還有另一種方法來完成同樣的事情?嵌套模板類型的部分專用化會在VC++ 2012編譯器中產生「內部錯誤」

enum Mutability {Const, Non_Const}; 

template <typename T, Mutability U> 
class Obj 
{ 
public: 
    template <Mutability V> 
    class Ref 
    { 
    public: 
     Ref() {} 

     friend class Obj; 
    }; 

    Obj() {} 
}; 

template <typename T> 
class Obj<T, Const>::template Ref<Non_Const> 
{ 
private: 
    Ref() {} 
}; //error C1001: An internal error has occurred in the compiler 

int main() 
{ 
    Obj<int, Const>::Ref<Non_Const> test; 
} 
+0

C1001基本上意味着編譯器崩潰等,一方面這是一個編譯器錯誤(VS2013做同樣的事情),但它也無法使用gcc進行編譯:http://ideone.com/BhT1bB –

+0

這非常糟糕 - 不是循環的,而是某種方式的循環聲明。 –

回答

0

如果你正在尋找做的是一個V作爲RefUMutability::const,我們可以使用一些模板弄虛作假執行這個概念不允許實例:

(有人比我聰明也許可以讓這個簡單)

enum class Mutability {Const, Non_Const}; 

template<Mutability T> 
struct ConstMutability: std::true_type{}; 

template<> 
struct ConstMutability<Mutability::Non_Const>: std::false_type{}; 

什麼我目前所做的就是地圖Mutability::Conststd::true_type,並Mutability::Non_Conststd::false_type

現在我可以用std::enable_if結合起來,強制執行以下是有效的組合:

  • UConstVConst
  • UNon_ConstVConst
  • UNon_ConstVNon_Const

全碼:

template <typename T, Mutability U> 
class Obj 
{ 
public: 
    template <Mutability V, typename std::enable_if< 
    std::is_same<ConstMutability<U>, ConstMutability<V>>::value || 
    (ConstMutability<V>::value && !ConstMutability<U>::value) 
    >::type* = nullptr> 
    class Ref 
    { 
    public: 
     Ref() {std::cout << "Successfully created a Ref object" << std::endl;} 

     friend class Obj; 
    }; 

    Obj() {} 
}; 

而且你可以測試正是如此:

int main() 
{ 
    Obj<int, Mutability::Const>::Ref<Mutability::Const> test1; //pass 
    //Obj<int, Mutability::Const>::Ref<Mutability::Non_Const> test2; // fail 
    Obj<int, Mutability::Non_Const>::Ref<Mutability::Const> test3; // pass 
    Obj<int, Mutability::Non_Const>::Ref<Mutability::Non_Const> test4; // pass 
} 

Live Demo

0

你想要做的是部分顯式地專門化一個成員類模板。這只是無效的C++,與基本試圖部分專門化一個成員相同的想法。這是不幸的VC崩潰試圖編譯這個,和gcc並沒有真正給予幫助的錯誤,但鐺恰巧:

main.cpp:21:31: error: cannot specialize a dependent template 
class Obj<T, Const>::template Ref<Non_Const> 
          ^

但是,您可以明確專門下來的整套方法:

template <> 
template <> 
class Obj<int, Const>::Ref<Non_Const> 
{ 
private: 
    Ref() {} 
}; 

然後你唯一的編譯錯誤是Ref()private

相關問題