C++ - g++ error: expected primary-expression

一 举例 

#include <iostream>

class Demo {
 public:
  template<typename T>
  void f(T&& t) {
    std::cout << "Demo:f " << std::endl;
  }
};

template <typename T>
class Demo_T {
 public:
  void f(T* t) {
    t->f<int>(1);
  }
};

int main() {
  Demo_T<Demo> dt;
  Demo d;
  dt.f(&d);
  std::cin.get();
  return 0;
}

二 关键字typename template

整理stackoverflow上的一个回答。

1 什么是名称查找(name lookup)

 C++ Standard  at (3/7):

Some names denote types or templates. In general, whenever a name is encountered it is necessary to determine whether that name denotes one of these entities before continuing to parse the program that contains it. The process that determines this is called name lookup.

 某些名称表示类型或模板。通常,只要遇到名称就需要在继续解析包含它的程序前确定该名称是否表示这些实体之一。确定的过程叫做名称查找。

2 什么是依赖名称(dependent name)

针对 t::x,如果t是一个模板类型参数,x可以是一个静态整型数据成员,也可以是一个嵌套类或者能够进行声明的typedef,如果名称具有在实际模板参数已知前无法查找的属性,就被称为依赖名称。

3 在依赖名称前使用typename

C++ Standard  at (14.6/2):

A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename.

 在模板声明或者定义中使用的名称和依赖于模板参数的名称,假设它们不会用来命名类型,除非适用的名称查找找到用typename关键字限定的类型名称或名称。也就是说

We decide how the compiler should parse this. If it is a dependent name, then we need to prefix it by typename to tell the compiler to parse it in a certain way. 

 我们决定编译器如何解析它,如果是一个依赖名称,我们需要在其前面加上typename关键字。

4 关键字template

对名称来说,模板也有类似的问题。

例如

boost::function< int() > f;

人可能会比较好理解。boost::function是一个模板,但是编译器理解会比较困难。例如对于下面代码来说:

namespace boost { int function = 0; }
int main() { 
  int f = 0;
  boost::function< int() > f; 
}

该表达式也是有效的(先判断小于,再判断大于)。所以不如告诉编译器这是一个模板,即在前面加上关键字template,例如

t::template f<int>(); // call a function template

 注意template可以出现的位置: 

Template names can not only occur after a :: but also after a -> or . in a class member access. You need to insert the keyword there too:

this->template f<int>(); // call a function template

三 参考

 Where and why do I have to put the “template” and “typename” keywords?

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值