强制类型的C ++模板 [英] Force type of C++ template
本文介绍了强制类型的C ++模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个基本的模板类,但我想限制专业化的类型为一组类或类型。例如:
I've a basic template class, but I'd like to restrain the type of the specialisation to a set of classes or types. e.g.:
template <typename T>
class MyClass
{
.../...
private:
T* _p;
};
MyClass<std::string> a; // OK
MYCLass<short> b; // OK
MyClass<double> c; // not OK
这些只是示例,允许的类型可能会有所不同。
Those are just examples, the allowed types may vary.
这是可能吗?如果是,怎么办?
Is that even possible? If it is, how to do so?
谢谢。
推荐答案
>另一个版本是为禁止类型保留未定义
Another version is to leave it undefined for the forbidden types
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
这篇关于强制类型的C ++模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文