Why is std :: plus a template template?

C ++ functor std::plusis implemented as

template<typename T>
struct plus
{
  constexpr T operator+(const T& lhs, const T& rhs) const
  { return lhs+rhs; }
};

but there is also specialization

template<>
struct plus<void>
{
  template< class T, class U>
  constexpr auto operator()(T&& lhs, U&& rhs) const
  -> decltype(std::forward<T>(lhs) + std::forward<U>(rhs))
  { return    std::forward<T>(lhs) + std::forward<U>(rhs); }
};

which has the advantage that it can work on any type, even different types, as long as it is defined T+U(for example, std::stringand const char*).

I was wondering why struct std::plusit is not defined as a non-template with existing functionality std::plus<void>? Are there any possible applications that cannot be satisfied with such an implementation?

Of course, this may have historical reasons (so it cannot be changed). But if this is the only reason, have you failed to change the default template argument to void?

template<typename T=void> struct plus;

. , cppreference plus<T> plus<void> ++ 14.


, plus<void>::operator+ C98 ++,

struct plus
{
  template<class T>
  T operator()(const T&lhs, const T&rhs) const
  { return lhs + rhs; }
};

, plus<T>, . ? / ? ( " , " )

+4
2

- ++ ( , ). , std::plus , .

+3

, :)

, std::plus , , , +, , , +.

+1

Source: https://habr.com/ru/post/1611653/


All Articles