我有一个基本的模板类,但我想限制一组类或类型的特化类型.例如:
template <typename T>
class MyClass
{
.../...
private:
T* _p;
};
MyClass<std::string> a; // OK
MYCLass<short> b; // OK
MyClass<double> c; // not OK
Run Code Online (Sandbox Code Playgroud)
这些只是示例,允许的类型可能会有所不同.
这甚至可能吗?如果是,怎么办?
谢谢.
Joh*_*itb 17
另一个版本是禁止类型的未定义
template<typename T>
struct Allowed; // undefined for bad types!
template<> struct Allowed<std::string> { };
template<> struct Allowed<short> { };
template<typename T>
struct MyClass : private Allowed<T> {
// ...
};
MyClass<double> m; // nono
Run Code Online (Sandbox Code Playgroud)
我想一个快速的想法,我确信有更好的方法:
template <typename T> struct protector {
static const int result = 1;
};
template <> struct protector<double> {
static const int result = -1;
};
template <typename T>
class MyClass
{
private:
char isfine[protector<T>::result];
};
Run Code Online (Sandbox Code Playgroud)
但是,对您的代码进行严格评论以防止用户使用错误类型进行实例化可能会更好:-)
看看Boost Concept Check Library:http: //www.boost.org/doc/libs/1_42_0/libs/concept_check/concept_check.htm