How to check the data type of a variable at compile time?

closed account (EUoNwbRD)
I want to use `constexpr` to check data types at compile time. The code is the following:

1
2
3
4
5
6
7
8
9
namespace toml {
  toml_table_t* parse(auto data) {
    if constexpr(typeid(data) == typeid(FILE*)) {
      return toml_parse_file(data);
    } else if constexpr(typeid(data) == typeid(char*)) {
      return toml_parse(data);
    }
  }
}


I want to check the data type of "data" for every function (template) call. When I'm running the following code, I'm getting a big error message (classic C++) but the highlights is: call to non-‘constexpr’ function ‘bool std::type_info::operator==(const std::type_info&) const

So is there a way to do that without get the error?
Last edited on
Use std::same_as or std::is_same_v
https://en.cppreference.com/w/cpp/concepts/same_as
https://en.cppreference.com/w/cpp/types/is_same

Scroll down on the linked reference pages for examples

You could also use simple function overloading to make this choice.
Last edited on
closed account (EUoNwbRD)
You could also use simple function overloading to make this choice.


Man, I swear, I had forget about function overloading and in this case it makes sense. Thanks a lot for your help man! Have an amazing day!
Topic archived. No new replies allowed.