模板约束C ++ [英] Template Constraints C++

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

问题描述

在C#中,我们可以定义一个泛型类型,对可以用作泛型参数的类型强加约束。以下示例说明了通用约束的用法:

In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints:

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 ++中模板参数的约束。

Is there a way we can impose constraints for template parameters in C++.

C ++ 0x本地支持这个,但我说的是当前的标准C ++ 。

C++0x has native support for this but I am talking about current standard C++.

推荐答案

正如别人已经提到的,C ++ 0x正在将这个内置于语言中。在此之前,我建议您 Bjarne Stroustrup 模板约束建议

As someone else has mentioned, C++0x is getting this built into the language. Until then, I'd recommend Bjarne Stroustrup's suggestions for template constraints.

编辑: Boost 还有一个自己的替代品

Edit2:看起来像概念已从C ++ 0x删除

Looks like concepts have been removed from C++0x.

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

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