在C++中为用户定义的类型专门化std::minus是否合法?

是否标准库允许用户专门函数对象一样std::plus,并std::minus为自定义类型?

如果我的第一个问题的答案是肯定的,是否允许用户更改呼叫运营商的声明?例如,由于 C++14 std::minus::operator() 声明如下:

constexpr T operator()( const T& lhs, const T& rhs ) const;

更改此运算符使其不再constexpr或返回double而不是 T 是否合法?

namespace std
{
    template <> 
    struct minus<MyArrayType>
    {
        double operator ()(const MyArrayType& x, const MyArrayType& y) const
        {
            return l2_norm(x - y);
        }
    };
}   // std

回答

The rules for extending namespace std says:

It is allowed to add template specializations for any standard library class template to the namespace std only if the declaration depends on at least one program-defined type and the specialization satisfies all requirements for the original template, except where such specializations are prohibited.

(emphasis mine)

So in your case, adding a specialization for the program-defined type MyArrayType would work.

但是,成员的返回类型operator() 必须MyArrayType,而不是double。此外,该成员operator() 必须constexpr

违反其中任何一个都意味着专业化不满足主模板的要求。


以上是在C++中为用户定义的类型专门化std::minus是否合法?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>