在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 ++。
3 回答

FFIVE
TA貢獻1797條經驗 獲得超6個贊
您可以在不執行任何操作的IFoo上放置一個保護類型,確保它在Foo中的T上存在:
class IFoo
{
public:
typedef int IsDerivedFromIFoo;
};
template <typename T>
class Foo<T>
{
typedef typename T::IsDerivedFromIFoo IFooGuard;
}

繁華開滿天機
TA貢獻1816條經驗 獲得超4個贊
如果使用C ++ 11,則可以使用static_assertwith 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");
// ...
}
}
- 3 回答
- 0 關注
- 552 瀏覽
添加回答
舉報
0/150
提交
取消