xuhdev
xuhdev

Reputation: 9333

Define a template function taking a parameter of a template class

There is a template class

template <class T0, class T1, ....... > // many template parameters
class Foo { ...... }

How can I define a template function to accept Foo with any template parameters?

The function can be operator <<, in which case defining a single template parameter would often break the compilation. C++ 11 solution is welcome.

Upvotes: 1

Views: 53

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477040

You can define a function template like this:

template <typename ...Args>
void f(Foo<Args...> foo)
{
    // ...
}

Upvotes: 2

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

The most obvious approach would be

template <typename... T>
std::ostream& operator<< (std::ostream& out, Foo<T...> const& value) {
    return out << "Foo(...)";
}

This version is more specialized than a version taking just one template argument. If you were to define this operator with just one template argument you'd need to determine the template actually does fit the definition of Foo<T...> and otherwise remove it from the overload set. Although this can be done, relying on partial ordering of overloads seems to be simpler in this case.

Upvotes: 2

Related Questions