可能重複:
C++ Restrict Template Function
Is it possible to write a C++ template to check for a function's existence?是否可以限制模板?
是否有可能以限制其模板可以實例 的類型(即,有一個編譯錯誤,如果我用template<type_not_allowed>
)?
可能重複:
C++ Restrict Template Function
Is it possible to write a C++ template to check for a function's existence?是否可以限制模板?
是否有可能以限制其模板可以實例 的類型(即,有一個編譯錯誤,如果我用template<type_not_allowed>
)?
其中一種方法是不提供默認實現,並且只對您希望允許的類型專門化您的類模板。例如:
#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
}
您可以點擊這裏Restrict Template Function
我不能離開評論所以它是一個答案......
使構造私人的違法類型:
template<typename T>
class Z
{
public:
Z() {}
};
template<>
class Z<int>
{
private:
Z();
};
Z<float> f; // OK
Z<int> i; // Compile time error.
很好的答案,弄清楚一個例子: '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