编译时间模板限制C ++ [英] Compile Time Template restriction C++

查看:118
本文介绍了编译时间模板限制C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有4个班级:

  • OverVoid
  • 元:继承OverVoid
  • 物理:与以上无关
  • 移动:模板化的类

我希望move的模板仅接受OverVoid类型的对象,即Ove​​rVoid和Meta.

I want move's template to accept objects of only OverVoid type i.e. OverVoid and Meta.

class OverVoid{
public:

    virtual ~OverVoid(){
    };
};

class Meta: public OverVoid{

};

class Physical{
public:
};

template<typename _Ty>
class Move{

};

我希望在编译时抛出错误, 我知道有一种方法可以使用Boost,但是我不能使用Boost(我公司的开发问题)

I want an error to be trown at compile time, I know there is a way with boost but I cannot use Boost (dev issues with my company)

有什么想法吗?

推荐答案

您可以隐藏非OverVoid

template<typename _Ty, 
         class = typename std::enable_if<std::is_base_of<OverVoid, _Ty>::value>::type>
class Move{

};

当您尝试编译非OverVoid类型的类时,您会收到错误消息.

You then get an error when attempting to compile a class of non-OverVoid type.

int main() {

  Move<Meta> a;
  Move<OverVoid> b;
  Move<Physical> c;
  // your code goes here
  return 0;
}

错误:

prog.cpp: In function 'int main()':
prog.cpp:29:15: error: no type named 'type' in 'struct std::enable_if<false,    void>'
Move<Physical> c;

这篇关于编译时间模板限制C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆