【发布时间】:2020-01-23 08:22:50
【问题描述】:
能否告诉我为什么以下代码无法编译(在 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()。
【问题讨论】:
-
您的意思是写
std::declval<double>()或double()而不仅仅是double?目前,您正在尝试将值和类型相乘。 -
@Kerndog73 啊,是的。
std::declval<double>()和double()有区别吗? -
可能不会。
std::declval用于不一定是默认可构造的类型。std::declval<T>()总是比T()好,但如果你知道它是double,那么你可以写double()。 -
@Kerndog73 我解决了这个问题(如问题),但它仍然给出同样的错误!
标签: c++ templates c++14 sfinae decltype