0

I have a function template defined as follows:

template <typename T>
Test &operator<<(const T &data)
{
    std::cout << data << std::endl;
    return *this;
}

As you can see, I print out to the console data using std::cout, which type is std::ostream. However, T may not be a type handled by std::ostream::operator<<.

That's why I'd like to add a static_assert to check whether T is accepted by the insertion operator or not. Currently, I must do a check for every type that std::ostream::operator<< accept:

template <typename T>
Test &operator<<(const T &data)
{
    static_assert(std::is_arithmetic<T>::value ||
                  std::is_same<T, std::streambuf*>::value ||
                  ...
                  std::is_same<T, std::string>::value, "data type must be compliant to std::ostream::operator<< accepted types");

    std::cout << data << std::endl;
    return *this;
}

Is there a type trait that automatically do that? What would you do?

GuiTeK
  • 1,561
  • 5
  • 20
  • 39
  • 1
    First off, you can't print a type. So, `std::cout << T << std::endl` is wrong in the first place. What you probably meant is `std::cout << data << std::endl;`. Second I don't see the point in this. If `T` isn't printable `std::cout` will complain and you'll get the error you want. – 101010 Aug 08 '14 at 12:16
  • Yes sorry I meant `std::cout << data << std::endl` of course, my mind was probably elsewhere when I wrote it. – GuiTeK Aug 08 '14 at 12:26
  • 2
    @GuiTeK Do you have any particular need to catch that error? If `operator<<` is not overloaded for `T`, the compilation will fail anyway (due to `static_assert` or overload resolution). – edmz Aug 08 '14 at 12:36

1 Answers1

2

Why do you want a static_assert? Is it acceptable to simply make the function not callable if the insertion isn't valid?

template <typename T>
auto operator<<(const T &data) -> decltype(std::cout << data, std::declval<Test&>())
{
    std::cout << data << std::endl;
    ...
}

If you really want a trait see is_stream_insertable

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521