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

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

本文关键字:编译 函数调用 模板方法 C++11      更新时间:2023-10-16

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

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

如果我#if 0更改为#if 1g++ 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<

这是一个演示。