这个问题在这里已经有了答案:
using std::is_same, why my function still can't work for 2 types
(4 个回答)
去年关闭。
编译器在构建过程中不断分配不兼容的类型。
错误信息:
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 起)。
If the value is
true
, then statement-false is discarded (if present), otherwise, statement-true is discarded.
例如
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();
}