C++11:模板方法的模板函数调用不编译?

C++11: template function call of a template method doesn't compile?

以下程序,如果按所示编译,输出 size: 1 align: 1.

但是,尝试从模板化函数调用相同的方法模板是行不通的。

如果我将 #if 0 更改为 #if 1,g++ 9.2.1 会出现错误 expected primary-expression before 'char'。 clang++ 听起来更有帮助 error: use 'template' keyword to treat 'log' as a dependent template name 但我不确定它希望模板出现在哪里。

那么是什么给了?

#include <iostream>
using namespace std;



class Foo {

public:
  Foo() {};
  ~Foo() {};
  void log( int iSizeItem, int iAlignItem ) {
    cout << "size: " << iSizeItem << "  align: " << iAlignItem << endl;
  }
  
  template<class T> void log() {
    log( sizeof( T ), alignof( T ) );
  }
};


#if 0
template<class T> void Test( T& t ) {
  t.log<char>();
}
#endif


int main( int nArg, char* apszArg[] ) {
  Foo foo;
  foo.log<char>();

  //Test( foo );

  return 0;
}

你需要指定log是一个函数模板,像这样:

template<class T> void Test( T& t ) {
  t.template log<char>();
}

否则编译器不知道log是否是T的成员,而<实际上是operator<.

这是 demo