是否可以根據string編譯時已知的型別獲取型別?主要與constexpr std::string_view.
#include <bits/stdc .h>
template <std::string_view>
struct MakeType {};
template <>
struct MakeType<"int"> {
using type = int;
};
template <>
struct MakeType<"float"> {
using type = float;
};
int main() {
constexpr std::string_view my_int = "int";
MakeType<my_int>::type i = 5;
return 0;
}
uj5u.com熱心網友回復:
是的,你可以做這樣的事情,即使我目前不明白我們為什么需要它。但它不起作用,std::string_view因為我們需要一種包含物件本身資料的資料型別。由于 C 20 提供了一種通過模板引數定義 constexpr 字串型別的簡單方法,因此我們擁有所需的一切!
template<size_t N>
struct mystring
{
std::array<char, N> arr_;
constexpr mystring(const char(&in)[N]) : arr_{}
{
std::copy(in, in N, arr_.begin());
}
};
template < mystring s > struct MakeType { using type=void;};
template <> struct MakeType<"int"> {using type=int;};
template <> struct MakeType<"double"> {using type=double;};
template < mystring T>
using MakeType_t = MakeType<T>::type;
int main()
{
MakeType_t<"int"> xi=9;
MakeType_t<"double"> xd=10.234;
std::cout << xi << std::endl;
std::cout << xd << std::endl;
static_assert( std::is_same_v< double, MakeType_t<"double">>);
static_assert( std::is_same_v< int, MakeType_t<"int">>);
}
看到它在這里在 gcc 上作業...... 也適用于 clang
備注:clang 需要額外的typename. 我相信 clang 在這里是錯誤的,因為在 C 20 中,額外的需求typename放寬了很多,但我不是語言律師。
uj5u.com熱心網友回復:
用 C 不可能。我不明白為什么有必要這樣做。如果您對字串“int”進行硬編碼,則可以將 int 硬編碼為型別說明符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/402509.html
標籤:
上一篇:訪問記憶體中的位
