模板约束 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++。

原文由 Jorge Ferreira 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 702
2 个回答

使用 C++20,是的,有: 约束和概念

也许你想保证一个模板是从一个特定的类派生的:

 #include <concepts>

template<class T, class U>
concept Derived = std::is_base_of<U, T>::value;

class ABase { };
class ADerived : ABase { };

template<Derived<ABase> T>
class AClass {
    T aMemberDerivedFromABase;
};

然后像往常一样编译以下内容:

 int main () {
    AClass<ADerived> aClass;
    return 0;
}

但是现在当你做一些违背约束的事情时:

 class AnotherClass {

};
int main () {
    AClass<AnotherClass> aClass;
    return 0;
}

AnotherClass 不是从 ABase 派生的,因此我的编译器 (GCC) 大致给出以下错误:

在函数’int main()‘中:注意:不满足约束注意:表达式’std::is_base_of::value [with U = ABase; T = AnotherClass]’ 评估为’假’ 9 |概念派生 = std::is_base_of::value;

正如您可以想象的那样,此功能非常有用,并且可以做的不仅仅是将类限制为具有特定的基础。

原文由 Hugo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏