SFINAE 检查模板参数运算符
SFINAE check for template parameter operators
你能告诉我为什么下面的代码无法编译(在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;
}
相关文章:
- 如何使基类的运算符对基类的可变参数数可见(请参阅下面的代码)?
- 具有两个间接寻址运算符 (C++) 的函数参数的用途
- 运算符重载:"operator+"必须采用零个或一个参数
- 为什么数组大小信息可用于"sizeof"运算符和 delete[] 运算符,但在将数组作为参数传递到
- 参数相关查找和流运算符重载
- C++:使用运算符 = 调用多参数构造函数
- 了解布尔运算符==(参数 1,参数 2)
- 我能否根据其运算符()的签名专门化可变参数模板参数
- SFINAE 检查模板参数运算符
- 不允许运算符 const 参数调用 const 成员函数
- 为私有结构定义双参数运算符重载
- C++ 通过自定义赋值运算符隐式转换函数参数
- 函数参数变量总是需要 & 或 * 运算符吗?
- 有条件地将默认参数传递给函数(使用"?"运算符)
- 可变参数模板参数转发使用逗号运算符
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 具有两个或多个模板参数的 C++ assigment 运算符
- 将多个参数传递给运算符 []
- 如何使用类的参数重载运算符+?
- 不允许在C++中使用多参数运算符 [] 的根本原因