Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to provide default template parameter and template function argument default value in the same time?

Tags:

c++

templates

I Have the following code:

template <typename Iter, typename STREAM>
void print(Iter b, Iter e, STREAM& strm)
{
    while (b != e)
    {
        strm << *b;
        strm << "   ";
        ++b;
    }
    strm << "\n";
}

How to have default value for strm = std::cout ?

like image 495
NarekMeta Avatar asked Feb 21 '26 14:02

NarekMeta


2 Answers

If you were to just add = std::cout, you'd need to provide the template argument std::ostream explicitly when calling the function with two arguments, which is a bit rubbish.

The easiest way to do what you want is to provide a new overload:

template <typename Iter>
void print(Iter b, Iter e)
{
    print(b, e, std::cout);
}

You could also consider getting rid of STREAM entirely; you usually only ever want to stream to a std::ostream. There's a reason a bunch of useful types inherit from it.

like image 198
Asteroids With Wings Avatar answered Feb 24 '26 03:02

Asteroids With Wings


You have to provide default for type and for argument:

template <typename Iter, typename STREAM = std::ostream>
void print(Iter b, Iter e, STREAM& strm = std::cout);

Demo

As std::cout is not a good default value for other STREAM, you probably need to change the default:

template <typename STREAM>
STREAM& DefaultStream;

template <>
std::ostream& DefaultStream<std::ostream> = std::cout;

and then

template <typename Iter, typename STREAM = std::ostream>
void print(Iter b, Iter e, STREAM& strm = DefaultStream<STREAM>);
like image 21
Jarod42 Avatar answered Feb 24 '26 04:02

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!