Search code examples
c++templatesif-statementfunction-templatestemplate-classes

Compiler error `assigning incompatible type within if statement`


The compiler keeps assigning incompatible types during the build.

error Message:

error: assigning to 'int' from incompatible type 'QString'
typeduserproperty.cpp:115:28: note: in instantiation of member function 'core::TypedUserProperty<int>::setValue' requested here

Sample code

 /**
  * @brief setValue
  * set value to property
  * @param val
  * value to set to property
  * @return
  * true - successfully set value
  * false - invalid value
  */
template<class T>
void TypedUserProperty<T>::setValue(QVariant val)
{

   if (std::is_same<T, int>::value == true) 
   {
      this->_value = val.toInt();
   }
   else if (std::is_same<T, QString>::value == true)
   {
      this->_value = val.toString();
   }
   else if (std::is_same<T, double>::value == true)
   {
      this->_value = val.toDouble();
   }
}

this->_value = val.toString(); is the line the error occurs

"_value" is data type template T

in this case i'm setting the T Template as an 'int'

does anyone know why this is occuring or if theres a workaround.


Solution

  • The problem is, even if you specify the template argument as int, those else parts have to be instantiated at compile-time.

    You can apply Constexpr If (since C++17).

    If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded.

    e.g.

    if constexpr (std::is_same<T,int>::value == true) {
        this->_value = val.toInt();
    } else if constexpr (std::is_same<T,QString>::value == true) {
        this->_value = val.toString();
    } else if constexpr (std::is_same<T,double>::value == true){
        this->_value = val.toDouble();
    }