强制类型的C++模板

gre*_*eth 12 c++ templates

我有一个基本的模板类,但我想限制一组类或类型的特化类型.例如:

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)

  • +1.事实上,我比第一个答案更喜欢这个解决方案. (2认同)

Ale*_*ler 8

我想一个快速的想法,我确信有更好的方法:

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)

但是,对您的代码进行严格评论以防止用户使用错误类型进行实例化可能会更好:-)

  • 有没有其他方法可以做到这一点,而不会在每个实例中产生char [1]数组的成本?就个人而言,我会使用BOOST_STATIC_ASSERT. (4认同)
  • 在`char`之前添加`typedef`. (2认同)
  • @Alexandre:我可能会使用白名单而不是黑名单,因为很难猜出用户要创建哪些类型. (2认同)