【问题标题】:calling a template function on a auto type-inferred variable in a template class [duplicate]在模板类中的自动类型推断变量上调用模板函数[重复]
【发布时间】:2015-09-05 04:39:00
【问题描述】:

此问题发生在带有类型化测试用例的 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;
}

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-19
      • 1970-01-01
      • 2019-11-29
      • 2021-03-04
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多