SFINAE 检查模板参数运算符
SFINAE check for template parameter operators
你能告诉我为什么以下代码无法编译(在 MSVC 中使用 "no matching overloaded function found"):
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
for T
returns T&&
,不允许将*=
(或其他赋值操作)的结果赋值给R值.
如果你想获得左值使用: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;
}
你能告诉我为什么以下代码无法编译(在 MSVC 中使用 "no matching overloaded function found"):
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
for T
returns T&&
,不允许将*=
(或其他赋值操作)的结果赋值给R值.
如果你想获得左值使用: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;
}