从编译时已知的字符串中检索类型

Retrieve a type from a string known at compile time

是否可以根据编译时已知的 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;
}

是的,你可以做这样的事情,即使我目前不明白我们为什么需要它。但它在 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">>);
}

See it working here on gcc ... also for clang

备注:clang 需要额外的 typename。我相信这里的 clang 是错误的,因为在 C++20 中,额外 typename 的需求放宽了很多,但我不是语言律师。