1

I have a templated class with one template parameter on it, and it has a method on it that is also templated, with different parameters. Here's a very simple example:

#include <vector>

template <typename A>
struct X {
    template <typename R>
    R get() { return R(); }
};

In a normal method, I can call X::get just fine; for example, this method compiles just fine:

int untemplated_function() {
    X<void> x;
    return x.get<int>();
}

But! I cannot seem to call this templated method from within a call where template parameter A on X is itself templated. For example, this method:

template <typename B>
int templated_function() {
    X<B> x;
    return x.get<int>();
}

Does not compile, giving me the error message:

<source>: In function 'int templated_function()':
<source>:12:18: error: expected primary-expression before 'int'
     return x.get<int>();
                  ^~~
<source>:12:18: error: expected ';' before 'int'
     return x.get<int>();
                  ^~~
<source>:12:21: error: expected unqualified-id before '>' token
     return x.get<int>();

Here's the full example on Godbolt

It is especially interesting to me that compilation fails even without instantiating the function template (I don't have to call or refer to templated_function<blah> for the compilation error to happen). If you remove any of the templates in the example, it compiles fine — for example, if you make X untemplated but keep X::get templated, it compiles.

How I can call X<A>::get<int>() from within a function where A is a template parameter?

Haldean Brown
  • 12,411
  • 5
  • 43
  • 58

0 Answers0