我有一個模板結構,我希望每個指標型別都實體化 const 版本,以避免出現重復的模板。這不起作用,但它適用于 char 指標。我怎樣才能使它與任何指標一起作業?
#include <iostream>
template<class T>
struct Foo {
static void bar() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
// Doesn't work
// template<class T>
// struct Foo<T*> : Foo<const T*> {};
// Works
template<>
struct Foo<char*> : Foo<const char*> {};
int main() {
Foo<char*>::bar();
}
uj5u.com熱心網友回復:
由于T也可以是T const,您正在創建無限繼承,因此不完整的型別錯誤。
由于const T*比賽T*用T是char const例如,您使類從自身繼承來繼承從Foo<T const*>,擴展到Foo<char const const*>其折疊到Foo<char const*>。
只需添加一個約束,您的代碼就會按預期作業:
// Now works
template<class T> requires (not std::is_const_v<T>)
struct Foo<T*> : Foo<const T*> {};
活生生的例子
uj5u.com熱心網友回復:
如果從Foo以下位置提取基類,則可以執行此操作:
#include <iostream>
template<class T>
struct FooImpl {
static void bar() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
template<class T>
struct Foo : FooImpl<T> {};
template<class T>
struct Foo<T*> : FooImpl<const T*> {};
int main() {
Foo<char*>::bar();
Foo<const char*>::bar();
}
與@Guillaume 的回答不同,這不需要 C 20。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/346656.html
