c++ - 模板约束 C++

标签 c++ templates constraints

在 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 对此有 native 支持,但我说的是当前标准 C++。

最佳答案

如果你使用 C++11,你可以使用 static_assertstd::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");

        // ...
    }
}

关于c++ - 模板约束 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/122316/

相关文章:

swift - 编程约束未按预期工作

c# - DataTable 上的 UNIQUE 约束

c++ - 转换运算符的 move 语义

c++ - C++ FakeIt 库多重继承

c++ - 编译失败,出现 "relocation R_X86_64_32 against ` .rodata.str1。 8' can not be used when making a shared object"

c++ - 在 void 函数的末尾有一个空的 return 语句的原因吗?

c++ - 与模板类 : Compile error 成为 friend

c++ - 成员函数的显式模板特化

c++ - 通用 Lambda 之间的差异

haskell - 递归类型的约束