【发布时间】:2012-06-02 11:38:12
【问题描述】:
我正在尝试编写非成员运算符函数模板,例如:
#include <utility>
template < typename T, unsigned L >
class MyType;
template < typename T, typename U, unsigned L >
auto operator ==( MyType<T,L> const &l, MyType<U,L> const &r )
-> decltype( std::declval<T>() == std::declval<U>() )
{ /*...*/ }
但是当我尝试处理 l 和 r 的长度不同时:
template < typename T, unsigned Lt, typename U, unsigned Lu, class Enable = typename std::enable_if<(Lt < Lu)>::type >
auto operator ==( MyType<T,Lt> const &l, MyType<U,Lu> const &r )
-> decltype( std::declval<T>() == std::declval<U>() )
{ /*...*/ }
template < typename T, unsigned Lt, typename U, unsigned Lu, class Enable = typename std::enable_if<(Lt > Lu)>::type >
auto operator ==( MyType<T,Lt> const &l, MyType<U,Lu> const &r )
-> decltype( std::declval<T>() == std::declval<U>() )
{ /*...*/ }
我得到模棱两可的错误。我试过类似的东西:
template < typename T, unsigned Lt, typename U, unsigned Lu, bool B = (Lt < Lu), class Enable = typename std::enable_if<B>::type >
auto operator ==( MyType<T,Lt> const &l, MyType<U,Lu> const &r )
-> decltype( std::declval<T>() == std::declval<U>() )
{ /*...*/ }
template < typename T, unsigned Lt, typename U, unsigned Lu, bool B = (Lt > Lu), class Enable = typename std::enable_if<B>::type >
auto operator ==( MyType<T,Lt> const &l, MyType<U,Lu> const &r )
-> decltype( std::declval<T>() == std::declval<U>() )
{ /*...*/ }
我已阅读(在 S.O. 上)为成员函数模板解决此类问题。 (有时,受访者将成员函数更改为成员函数模板以启用此功能。)但错误对我来说并没有改变。我是否必须切换到将enable_if 放入返回类型中?
哦,当两个元素类型无法比较时,返回类型表达式应该排除这个运算符。它真的会起作用吗?是否也可以将enable_if 放在那里?
【问题讨论】:
-
歧义错误到底是什么?
标签: c++ templates c++11 sfinae