简体   繁体   中英

How can I use template template type as an function argument?

I want to implement the following code:

template <int i>
void f() {
    ...
}
template <template <int i> typename Func>
void g(Func func, int i) {
    if (i == 0) func<0>();
    else if (i == 1) func<1>();
    else if (i == 2) func<2>();
    else assert(false);
}
int main() {
    g(f, 0);
}

However, this code can not be compiled. It says "error: argument list for template template parameter "Func" is missing". I don't know how to fix it. Thank you very much!

Templates can be used as arguments to templates, but they cannot be used as arguments to functions. Hence the error; when you tried to use a template name ( Func ) as the type of a function parameter, the compiler complained that a template name by itself is not enough. A template argument list is needed to get a type out of the template, and only then can it be the type of a function parameter.

It looks like you are trying to replicate the template parameter as a function parameter. Don't do that. Use the template parameter directly.

template <template<int> typename Func>
void g(int i) {
    if (i == 0) Func<0>();
    else if (i == 1) Func<1>();
    else if (i == 2) Func<2>();
    else assert(false);
}

However, there is a further problem with your setup. As suggested by the typename keyword, a template template argument cannot be a function template. So this does not work. See Can a template template parameter be of a variable or function?


An alternative (brought up by the OP) might be to use a class template and operator() . One caveat is that operator() cannot be static, so there is another syntactical change to g .

template <template<int> typename Func>
void g(int i) {
    if (i == 0) Func<0>{}();      // <
    else if (i == 1) Func<1>{}(); // < -- Invoke operator() on a temporary
    else if (i == 2) Func<2>{}(); // <
    else assert(false);
}

Given a class template f , this could be invoked via g<f>(0) .

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