Home > OS >  Retrieve a type from a string known at compile time
Retrieve a type from a string known at compile time

Time:01-04

Is it possible to get a type according to a string known at compile time? Mainly with 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;
}

CodePudding user response:

Yes, you can do such things, even if I currently did not see why we need it. But it did not work on base of std::string_view as we need a data type which contains the data in the object itself. As C 20 offers a simple way to define a constexpr string type via template parms, we have all what we need!

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

Remark: clang requires an additional typename. I believe clang is wrong here, as in C 20 the need of additional typename was relaxed a lot, but I am not a language-lawyer.

CodePudding user response:

No not possible with c . I don't see why it would ever be necessary. If you hardcode the string "int" you can hardcode int as the type specifier.

  •  Tags:  
  • Related