Click here to Skip to main content
15,889,706 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This line from the code below does not compile
C++
cout << cfoobar<int>::cgoobar{};
However this line from the code below does compile
C++
cout << cfoobar<int>{};
Mysteriously it also compiles the line below if cfoobar is not templated
C++
cout << cfoobar::cgoobar{};
May I please inquire how to override the ostream insertion operator for the case shown here
import std.core;
using namespace std;

template<typename T>
struct cfoobar
{
	struct cgoobar {};
};
template<typename charType, typename T>
basic_ostream<charType>& operator << (basic_ostream<charType>& ostream, const cfoobar<T>&) { ostream << __FUNCSIG__; return ostream; }

template<typename charType, typename T>
basic_ostream<charType>& operator << (basic_ostream<charType>& ostream, const typename cfoobar<T>::cgoobar&) { ostream << __FUNCSIG__; return ostream; }

int main()
{
	cout << cfoobar<int>{};
	cout << cfoobar<int>::cgoobar{};
}


What I have tried:

Have tried placing override in class
Posted
Updated 30-Aug-21 1:13am

1 solution

This might be not as flexible as would want. Use typedef with explicit type instanciation. It might require some extra work for using it, but it is usually small indeed:
C++
using namespace std;
template<typename T> struct cfoobar
{
	struct cgoobar {};
};

template<typename T, typename charType = char>
basic_ostream<charType>& operator <<
                            (basic_ostream<charType>& os, const cfoobar<T>&)
{
	os << "overload 1:" << __FUNCSIG__; return os;
}

//do it in exact place you need such an overload
typedef cfoobar<int>::cgoobar int_cgoobar;
template<typename charType = char>
basic_ostream<charType>& operator <<
                           (basic_ostream<charType>& os, const int_cgoobar& c)
{
	os << "overload 2:"<< __FUNCSIG__; return os; 
}

int main()
{
	cout << cfoobar<int>{} << endl;
	cout << int_cgoobar{} << endl;
	return 0;
}

Potential problem are expected with the way you are using using ostream which is already defined in iostream. Use a different name, for instance os
C++
template<typename T, typename charType = char>
basic_ostream<charType>& operator << (basic_ostream<charType>& os, const cfoobar<T>&) { os<< __FUNCSIG__; return os; }

template< typename T, typename charType = char>
basic_ostream<charType>& operator << (basic_ostream<charType>& os, const int_cgoobar& c) { os<< __FUNCSIG__; return os; }
 
Share this answer
 
v4
Comments
CPallini 30-Aug-21 7:31am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900