我所尋找的是一種方法,即說。這對所有的專業都是一樣的:
我正在尋找一種方法來說明:所有的專業都是一樣的。
template <typename T>
結構 Foo {
using id_type = unsigned int; // this does not depend on T!
};
Foo::id_type theId; //不管專業化是什么,id_type總是一樣的。
我想訪問id_type而不需要指定專業化...
uj5u.com熱心網友回復:
你不可能完全擁有你所要求的東西。Foo不是一個類。Foo<T>是一個類,對于任何T。
你可以有一個持有id_type的非模板基數,
struct FooBase {
using id_type = unsigned int;
};
template <typename T>
struct Foo : FooBase{};
FooBase::id_type theId。
你可以為T
template <typename T = struct FooPlaceholder>
struct Foo {
using id_type = unsigned int; // this does not depend on T!
};
Foo<>::id_type theId。
然而,沒有什么能阻止我寫一個明確的Foo的特殊化,它缺乏(或重新定義)id_type。
template <> struct Foo< MyType> { };
template <> struct Foo< MyOtherType> { int id_type = 42; };
uj5u.com熱心網友回復:
代替id_type成為一個類(別名宣告)屬性,你可以讓它成為模板引數上的一個獨立的特質:
#include <type_traits>
//幫助者:與std::is_same比較,但對于來說
//模板模板引數型別引數。
template <template <typename>。typename, template <typename> typename>
struct is_same_primary_template : std::false_type {};
template <template <typename> typename TT>
struct is_same_primary_template<TT, TT> : std::true_type {};
template <template <typename>。typename TT, template <typename> typename UU>
constexpr bool is_same_primary_template_v{
is_same_primary_template<TT, UU>::value}。
template <typename T> struct Foo {};
template <template <typename> typename, typename Enable = void> struct id_type;
template <template <typename> typename TT>
struct id_type<TT, std::enable_if_t<is_same_primary_template_v<TT, Foo>> {
using type = int;
};
// ...
template <template <typename> typename TT>
using id_type_t = typename id_type<TT> ::type。
int main() { id_type_t<Foo> theId; }
但這種方法有一個缺點。由于特質是對特定型別的專門化,它將這些型別與特質的實作結合在一起(正如你希望對你的專門化的位置非常小心,與主模板的位置有關)。
在撰寫專業化時,要注意它的位置;否則,要讓它編譯將是一個點燃其自焚的試驗。
uj5u.com熱心網友回復:
只是基于Caleth的回答和隨之而來的評論的一個擴展。 你可以像這樣保護自己不受Foo的 "壞 "專門化影響:
//-------------------------------------------------------------------------
//來自Caleth的評論
結構 FooBase
{
using id_type = unsigned int;
};
template <typename T>
struct Foo : FooBase
{
};
FooBase::id_type theId{};
//-------------------------------------------------------------------------
//繞過FooBase的特殊化。
template<>
struct Foo<char>
{
};
//-------------------------------------------------------------------------
//編譯時檢查是否有人瘋了一個 "壞 "的專業化,pre C 20。
template<typename T>
void f(const Foo<T> & foo)
{
static_assert(std::is_base_of_v<FooBase, Foo<T> >)。
}
//-------------------------------------------------------------------------
//C 20概念,檢查FooBase。
template<typename T>
概念 HasFooBase = std::is_base_of_v<FooBase, T> 。
//只接受來自FooBase的型別。
void g(const HasFooBase auto& foo)
{
}
//-------------------------------------------------------------------------
int main()
{
Foo<int> foo;
Foo<char> bar。
f(foo)。
g(foo)。
f(bar); //不會編譯,錯誤C2607:靜態斷言失敗。
g(bar); // won't compile, error C7602: 'g': the associated constraints are not satisfied。
return 0;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/333960.html
標籤:
