Reputation: 7500
I want compiler to complain when I try to print instances of one class,
let's say T2
. In VS2013+ I can use:
template <typename T = float>
std::ostream & operator<<(std::ostream & os, const T2 & t2) {
static_assert(std::is_integral<T>::value, "Fail in << for T2");
return os;
}
however, that does not work in VS2012 (error C4519: default template arguments are only allowed on a class template
). Any ideas how to achieve this in VS2012?
Upvotes: 1
Views: 93
Reputation: 13876
"I want compiler to complain when I try to print instances of one class, let's say T2"
#include <iostream>
struct T1 { int a; };
struct T2 { int a; };
template <typename T>
std::ostream & operator<<(std::ostream & os, const T & t2)
{
static_assert(!std::is_same<T2, T>::value, "Fail in << for T2");
return os;
}
int main()
{
T1 t1;
T2 t2;
std::cout << t1; // Works
std::cout << t2; // Static assert fail
}
I'm not understanding. Doesn't this answer your question?
Upvotes: 0
Reputation: 85361
VS2012 has incomplete support of C++11. Default template arguments for function templates, being a C++11 feature, is supported starting with VS2013.
Maybe you can try this, but it is also using some C++11 features:
template <typename T>
auto operator<<(std::ostream & os, T const& t2) ->
typename std::enable_if<std::is_same<T, T2>::value, std::ostream&>::type
{
static_assert(false, "Fail in << for T2");
return os;
}
If that also doesn't work, I would just degrade gracefully for archaic crap like VS2012 and be done with it.
#if _MSC_VER < 1800
std::ostream& operator<<(std::ostream & os, T2 const& t2); // will fail at link time
#else
. . .
#endif
Upvotes: 1