在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
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法可以在C++中对模板参数施加约束.
C++ 0x本身支持这个,但我说的是当前的标准C++.