我希望能夠使用字面意思作為id來參考不同的型別。
template<auto>
using type = void;
template<>
using type<0> = int;
template<>
using type<1> = char;
template<>
using type<2> = string;
int main()
{
type<0> var0;
type<1> var1;
type<2> var2;
}
這樣做的結果是編譯器給我錯誤,因為C 中還不支持型別別名專業化。(實作這種功能所需的技術根本不存在)
uj5u.com熱心網友回復:
這將做到這一點,并將給你提供你需要的語法。請注意,我明確地使用了std::size_t,以避免在其他型別上的特殊化,而不是數字。
#include <string>
#include <type_traits>
//-------------------------------------------------------------------
//隱藏所有命名空間中的鍋爐板。
//使用結構來實作部分專業化。
命名空間詳細資訊
{
template<std::size_t N>
struct type_s { using type = void; };
template<> struct type_s< 0> { using type = int; };
template<> struct type_s< 1> { using type = char; };
template<> struct type_s<2> { usingtype = std::string; };
}
//-------------------------------------------------------------------
//現在你可以為別名使用一個完整的模板。
template<std::size_t N>
using type_t = typename details::type_s<N>:type。
//-------------------------------------------------------------------
int main()
{
type_t<0> var0{ 42 };
type_t<1> var1{ 'A'/span> };
type_t<2> var2{ "Hello World!" };
static_assert(std::is_same_v<type_t<0> ,int>)。
static_assert(std::is_same_v<type_t<1>, char>) 。
static_assert(std::is_same_v<type_t<2>, std::string>) 。
static_assert(std::is_same_v<decltype(var0), int>) 。
static_assert(std::is_same_v<decltype(var1), char>)。
static_assert(std::is_same_v<decltype(var2), std::string>) 。
}
uj5u.com熱心網友回復:
在別名模板中不允許部分專業化,但是,你可以使用std::conditional代替:
#include <type_traits>/span>
#include <string>
/ ...
template <auto X>
using type = std::conditional_t<X == 0, int,
std::conditional_t<X == 1, char,
std::conditional_t<X == 2, std::string,
void> >> 。
uj5u.com熱心網友回復:
幸運的是,我找到了一個解決方法,它使用了C 中支持的類專用化:
template<auto>
struct TypeAliasWrapper。
template<>
struct TypeAliasWrapper<0>{using type = int; };
template<>
struct TypeAliasWrapper<1>{using type = char; };
template<>
struct TypeAliasWrapper<2>{using type = string;}。
int main()
{
TypeAliasWrapper<0>:type var0。
TypeAliasWrapper<1>:type var1;
TypeAliasWrapper<2>:type var2;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/333966.html
標籤:
