在模板类中使用模板函数

Using a template function in a template class

本文关键字:函数      更新时间:2023-10-16

我有以下(简化)代码:

#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;
                          ^

(后面跟着几百行计数相关的错误)。我想它没有意识到A::f可以是一个模板函数?它是否违反了标准?

您需要将关键字template:

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

您需要放置它,因为A是一个依赖名称,否则编译器会将其解释为比较操作符:

A::f < B