Home > Back-end >  How to convert a variable from an int into a template parameter only if it is convertable in c
How to convert a variable from an int into a template parameter only if it is convertable in c

Time:09-17

I am trying to write a function that takes a variable of arbitrary type and sets it to an int value only if the type of the given variable can be converted to an int. My simplified code:

  template <typename T>
  void getInt(T& param)
  {
    int int_value = calculate_int_value();
    if(std::is_convertible_v<int, T>){
        param = static_cast<T>(int_value);  
    }
  }  

However, when I try to compile it, I get errors such as

error: no matching function for call to 'std::__cxx11::basic_string<char>::basic_string(int&)'

error: invalid conversion from 'int' to 'const char*'

Which makes me think I can't just convert an int value of arbitrary type inside an if statement, which proves it convertibility. How do I achieve my goal? Did I miss something?

CodePudding user response:

std::is_convertible_v was added in C 17, if your code uses it then this means that your compiler support C 17, which also has if constexpr:

if constexpr(std::is_convertible_v<int, T>){
    param = static_cast<T>(int_value);  
}

In a regular if, even if it always evaluates to false, whatever's in the if statement must still be valid C . Even if the body of a regular if statement is never executed it still must compile as valid C . Attempting to convert something to int when it is proven not to be convertible to an int will, of course, not work.

if constexpr makes it possible to do otherwise (as long as if itself is a compile-time constant expression). The body of the if statement must still be syntactically valid C , but only syntactically valid.

  • Related