在模板类中的自动类型推断变量上调用模板函数

时间:2015-06-19 08:58:41

标签: c++ c++11 gcc compiler-errors auto

此问题发生在带有键入测试用例的Google测试框架的上下文中。这里继承和模板是混合的,因此我们必须通过this->来引用基类的成员。下面的简短代码就是问题所在。

如果使用ref的第一个定义(1),则以下代码不会在gcc-4.9.2,gcc-5.1.0,clang-3.5上编译。如果使用第二个版本(2),clang甚至不编译。如果在(3)中使用实际类型(在http://gcc.godbolt.org/上测试),则编译正常。

我的问题是编译器是否适合不编译它以及为什么它们是正确的。或者,如果这是格式良好的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 个答案:

答案 0 :(得分:1)

编译器不知道ref.foo是模板,所以你需要告诉它:

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

语法有点奇怪,但请查看this question了解更多详情。

相关问题