模板约束C ++

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