简体   繁体   中英

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.

You can define a function template like this:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM