Search code examples
c++templateslambdaauto

Auto parameter type in lambda causes "Use 'template' keyword to treat..." error


I have this code

struct TestClass
{
    template <typename T>
    T get()
    {
        return 0;
    }
};

void invoke(const std::function<void(const TestClass& c)>& func)
{
    func(TestClass());
}

Now if I use invoke as following there is no problems

invoke([](TestClass tc) {
    tc.get<int>();
});

But if I change the parameter type in the lambda function to auto I get the following error. I know that I can fix it by inserting the template keyword before get, but what I'm not understanding is why I get this error?

error: use 'template' keyword to treat 'get' as a dependent template name
    tc.get<int>();
       ^
       template

// Happens when using `auto` as parameter type
invoke([](auto tc) {
    tc.get<int>();
});

I'm using clang v10.0


Solution

  • Now that you have a template type (in the form of auto) instead of a concrete type TestClass, the get function is dependent, and therefore you need to qualify it with the template keyword:

    tc.template get<int>();