假設我有一個類模板
template<class T>
class Foo{};
是否可以防止 T 成為 Foo 的實體化。也就是說,這不應該編譯:
struct Bar{};
Foo<Foo<Bar>> x;
uj5u.com熱心網友回復:
另外的選擇:
#include <type_traits>
template <typename T>
struct ValidFooArg;
template <typename T>
requires ValidFooArg<T>::value
class Foo
{
};
template <typename T>
struct ValidFooArg : std::true_type {};
template <typename T>
struct ValidFooArg<Foo<T>> : std::false_type {};
int main()
{
Foo<int> x; // ok
Foo<Foo<int>> y; // error
}
uj5u.com熱心網友回復:
在這種情況下,您可能仍會提供部分專業化以產生錯誤:
template <typename T>
constexpr bool always_false = false;
template<class T>
class Foo<Foo<T>>
{
static_assert(always_false<T>);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/532067.html
標籤:C 模板
上一篇:為什么我在終端中的java版本與idea中顯示的jdk版本不同?
下一篇:如何為自定義型別創建地圖模板
