【问题标题】:C++11: template function call of a template method doesn't compile? [duplicate]C++11:模板方法的模板函数调用不编译? [复制]
【发布时间】:2020-06-28 16:25:23
【问题描述】:

如果编译如下所示,以下程序将输出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;
}

【问题讨论】:

  • 我的问题显然也在以下综合问题下得到了回答:stackoverflow.com/questions/610245/… ...但是我发现这个问题过于宽泛。如果有什么东西应该像我的一样被分解成碎片,那更容易找到。

标签: c++ c++11 function-templates


【解决方案1】:

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

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

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

这是demo

【讨论】:

  • 在 g++ 9.2.1 和 clang++ 9.0.1 中完美运行。不知道你为什么投反对票!我从 1992 年就开始编写 C++,之前没有见过这种语法……
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多