模板约束C ++

在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 ++。


DIEA
浏览 501回答 3
3回答

FFIVE

您可以在不执行任何操作的IFoo上放置一个保护类型,确保它在Foo中的T上存在:class IFoo{public:&nbsp; &nbsp; typedef int IsDerivedFromIFoo;};template <typename T>class Foo<T>{&nbsp; &nbsp; typedef typename T::IsDerivedFromIFoo IFooGuard;}

繁华开满天机

如果使用C ++ 11,则可以使用static_assertwith std::is_base_of来实现此目的。例如,#include <type_traits>template<typename T>class YourClass {&nbsp; &nbsp; YourClass() {&nbsp; &nbsp; &nbsp; &nbsp; // Compile-time check&nbsp; &nbsp; &nbsp; &nbsp; static_assert(std::is_base_of<BaseClass, T>::value, "type parameter of this class must derive from BaseClass");&nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP