在 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_assert
和 std::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/