2011-12-02 153 views

回答

7

其中一種方法是不提供默認實現,並且只對您希望允許的類型專門化您的類模板。例如:

#include <iostream> 
using namespace std; 

template<class X> class Gizmo 
{ 
public: 
    Gizmo(); 
}; 

template<> Gizmo<int>::Gizmo() 
{ 
} 

int main() 
{ 
    Gizmo<float> gf; // ERROR: No specialization for Gizmo<float> results in a linking error 
} 
3

您可以點擊這裏Restrict Template Function

我不能離開評論所以它是一個答案......

+1

很好的答案,弄清楚一個例子: 'struct No {}; struct是:public No {};模板 struct myfunction_allower {enum {value = true}; }; template <> struct myfunction_allower {enum {value = false}; };模板 void myfunction(T){static_assert(myfunction_allower :: value,「type not allowed」); } void test(){myfunction(1。); struct否否; MyFunction的(否); //失敗,錯誤C2338:type not allowed struct是是; MyFunction的(是); //它的工作原理:禁止不是傳遞性的}' – reder

3

使構造私人的違法類型:

template<typename T> 
class Z 
{ 
public: 
    Z() {} 
}; 

template<> 
class Z<int> 
{ 
private: 
    Z(); 
}; 

Z<float> f; // OK 
Z<int> i; // Compile time error. 
+0

我想知道是否離開專業化不完整不會更簡單,仍然有訣竅? – UncleBens

+0

@UncleBens,這將產生一個鏈接器錯誤(我認爲這就是你的意思:'template <> class Z {public:Z();};'。正如我上面它產生一個編譯器錯誤,早期檢測 – hmjd

+1

不,我的意思是'template <> class Z ;'你不應該在編譯時實例化一個不完整的類型(基本上是相同的 - 但是是相反的 - 就像接受的答案一樣,如果基本模板不完整) – UncleBens

相關問題