C ++:只有子类的模板 [英] C++: Templates of child classes only

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

问题描述

有没有办法让一个模板只使用一个基类的子类?这样的东西:

Is there any way to make a template only work with child classes of a base class? Something like this:

template<BaseClass T>
class FooBar
{
    // ...
};


推荐答案

例如此推广示例),或者致电构造函数(或在使用代码时总是生成的其他代码)转换为采用BaseClass类型的无用功能,例如:

Either use a static assert from your favourite C++ library (such as this boost example), or put a call in the constructor (or other code which will always be generated when the code is used) to a do-nothing function taking a BaseClass type, for example:

template<class T>
class FooBar
{
public:
    FooBar () {
        Check(static_cast<T*>(0));
    }

private:
    void Check ( BaseClasse* ) {} 
};

(未测试)

这篇关于C ++:只有子类的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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