为了账号安全,请及时绑定邮箱和手机立即绑定

模板约束C ++

模板约束C ++

C++
DIEA 2019-11-13 16:11:05
在C#中,我们可以定义一个通用类型,该通用类型对可用作通用参数的类型施加了约束。以下示例说明了通用约束的用法:interface IFoo{}class Foo<T> where T : IFoo{}class Bar : IFoo{}class Simpson{}class Program{    static void Main(string[] args)    {        Foo<Bar> a = new Foo<Bar>();        Foo<Simpson> b = new Foo<Simpson>(); // error CS0309    }}有没有一种方法可以对C ++中的模板参数施加约束。C ++ 0x为此提供了本机支持,但是我正在谈论当前的标准C ++。
查看完整描述

3 回答

?
FFIVE

TA贡献1797条经验 获得超6个赞

您可以在不执行任何操作的IFoo上放置一个保护类型,确保它在Foo中的T上存在:


class IFoo

{

public:

    typedef int IsDerivedFromIFoo;

};


template <typename T>

class Foo<T>

{

    typedef typename T::IsDerivedFromIFoo IFooGuard;

}


查看完整回答
反对 回复 2019-11-13
?
繁华开满天机

TA贡献1816条经验 获得超4个赞

如果使用C ++ 11,则可以使用static_assertwith std::is_base_of来实现此目的。


例如,


#include <type_traits>


template<typename T>

class YourClass {


    YourClass() {

        // Compile-time check

        static_assert(std::is_base_of<BaseClass, T>::value, "type parameter of this class must derive from BaseClass");


        // ...

    }

}


查看完整回答
反对 回复 2019-11-13
  • 3 回答
  • 0 关注
  • 499 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信