你能告诉我为什么下面的代码编译失败(在MSVC中“没有找到匹配的重载函数”):
template<typename V>
struct LinearModel { // has basis vectors
template<typename T = V>
auto consolidation() const -> decltype(std::declval<T>() += (std::declval<T>() *= double())) {
V linearCombination;
// linearly combine basis vectors using += and *=
return linearCombination;
}
};
int main(){
LinearModel<double> lm;
auto c = lm.consolidation(); // the line that produces the error
return 0;
}我的意图是只为具有T& operator *=(double)和T& operator +=(T)的T定义LinearModel<T>::consolidation()。
发布于 2020-01-23 16:32:17
T的declval返回T&&,不允许将*= (或其他赋值操作)的结果赋给R-value。
如果您想获得左值,请使用:declval<T&>()
-> std::remove_reference_t<decltype(std::declval<T&>() += (std::declval<T&>() *= double{}))> 发布于 2020-01-23 16:53:05
根据@rafix07的回答,我最后做了什么:
template<typename T = std::remove_reference_t<decltype(std::declval<V&>() += (std::declval<V&>() *= double()))>>
T consolidation() const {
T linearCombination;
// ...
return linearCombination;
}https://stackoverflow.com/questions/59874162
复制相似问题