calling a template function on a auto type-inferred variable in a template class

85 views Asked by At

This problem occurred in the context of the google test framework with typed test cases. Here inheritance and templates are mixed such that we have to refer to members of the base class via this->. The short code below is what the problem boils down to.

The following code does not compile on gcc-4.9.2,gcc-5.1.0,clang-3.5 if the first definition (1) for ref is used. clang does not even compile if the second version (2) is used. all compile fine if the actual type is used as in (3) (tested on http://gcc.godbolt.org/ ).

My question is if the compiler(s) are right to not compile this and why they are right. Or if this is well formed c++11.

#include <iostream>
struct A {
    template<int e> void foo() { std::cout << e << std::endl; }
    void bar(){}
};
template<typename T> struct B {
    A a;
    void baz() {
        auto& ref = this->a; // (1)
        // auto& ref = a;       // (2)
        // A& ref = this->a;    // (3)
        static_assert(std::is_same<decltype(ref),A&>::value, 
                      "ref should have type A&");
        ref.bar();
        ref.foo<1>(); // this line causes a compile error
    }
};

int main() {
    B<int> b;
}
1

There are 1 answers

0
TartanLlama On BEST ANSWER

The compiler doesn't know that ref.foo is a template, so you need to tell it:

ref.foo<1>();
//change to
ref.template foo<1>();

The syntax is a bit bizarre, but have a look at this question for more details.