编译器在构建期间不断分配不兼容的类型。
错误消息:
error: assigning to 'int' from incompatible type 'QString'
typeduserproperty.cpp:115:28: note: in instantiation of member function 'core::TypedUserProperty<int>::setValue' requested here
样本代码
/**
* @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();
是发生错误的行
“ _ value”是数据类型模板T
在这种情况下,我将T模板设置为'int'
没有人知道为什么会这样或是否有解决方法。
问题是,即使您将模板参数指定为int
,也必须在编译时实例化这些else
部分。
您可以应用Constexpr If(自C ++ 17起。)>
如果值是
true
,则丢弃statement-false(如果存在),否则,丢弃statement-true。例如
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();
}