SFINAE 检查模板参数运算符

SFINAE check for template parameter operators

本文关键字:参数 运算符 检查 SFINAE      更新时间:2023-10-16

你能告诉我为什么下面的代码无法编译(在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()

declval对于T返回T&&,不允许将*=(或其他赋值操作(的结果分配给 R 值。

如果要获取Lvalue,请使用:declval<T&>()

-> std::remove_reference_t<decltype(std::declval<T&>() += (std::declval<T&>() *= double{}))> 

现场演示

我最后做了什么,基于@rafix07的回答:

template<typename T = std::remove_reference_t<decltype(std::declval<V&>() += (std::declval<V&>() *= double()))>>
T consolidation() const {
T linearCombination;
// ...
return linearCombination;
}