在模板类中使用模板函数

时间:2016-07-04 13:36:17

标签: c++ templates gcc

我有以下(简化)代码:

#include <iostream>

class Foo {
public:
  template<class T>
  static size_t f() {
    return sizeof(T);
  }
};

template<class A>
class Bar {
public:
  template<class B>
  static void f(B const& b) {
    std::cout << A::f<B>() << std::endl;
  }
};

int main() {
  Bar<Foo>::f(3.0);
  return 0;
}

它在MSVC中编译很好,但在GCC(5.2.1)中它会出现以下错误:

main.cpp:16:26: error: expected primary-expression before ‘>’ token
     std::cout << A::f<B>() << std::endl;
                          ^

(后面跟着几百条与cout相关的错误)。我想它没有意识到A::f可以是模板函数吗?是否打破了标准中的任何内容?

1 个答案:

答案 0 :(得分:3)

您需要设置关键字template

std::cout << A::template f<B>() << std::endl;

你需要把它放在一起,因为A是一个从属名称,否则编译器可以把它解释为比较运算符:

A::f < B
相关问题