可能重复:
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