C ++ 0x允许decltype()函数签名? [英] Does C++0x allow decltype() in function signature?

查看:207
本文介绍了C ++ 0x允许decltype()函数签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题显然假设我们不想使用这种类型的模板(无论什么原因)。

This question obviously assume that we don't want to use templates for this type (for whatever reasons).

class Product
{
public:
   Product( decltype(mPrice) price_, decltype(mLabel) label_ )  // 1.
      : mPrice( price_ ), mLabel( label_ )
   {}

   decltype(mPrice) price() const {return mPrice;} // 2.
   decltype(mLabel) label() const {return mLabel;} // 2.


private:

   float mPrice ; // type might later be changed to more acurate floating point abstraction
   std::string mLabel; // type might later be changed by a special localization-oriented string
};

问题是: 1。

The question is : are 1. and 2. allowed and possible (or even specifically defined) in C++0x?

推荐答案

所有你拥有的要做的是在之前声明 mPrice mLabel

All you have to do is declare mPrice and mLabel before you use decltype:

class Product
{
private:
   float mPrice ;
   std::string mLabel;
public:
   Product( decltype(mPrice) price_, decltype(mLabel) label_ )  // 1.
      : mPrice( price_ ), mLabel( label_ )
   {}

   decltype(mPrice) price() const {return mPrice;} // 2.
   decltype(mLabel) label() const {return mLabel;} // 2.
};

这在g ++ 4.4下用-std = c ++ 0x进行编译。

This compiles fine under g++ 4.4 with -std=c++0x.

编辑关键是,编译器必须能够在第一遍上解析函数声明。成员函数的主体可以在解析成员声明之后编译,但是成员声明本身必须立即可以理解 - 否则,可恶的编译器在哪里开始?

Edit The point is, the compiler has to be able to parse function declarations on the first pass. The body of a member function can be compiled after the member declarations have been parsed, but the member declarations themselves have to be immediately intelligible -- otherwise, where does the poor compiler start?

因此,每个成员函数参数的类型必须在遇到时立即知道。

So the type of every member function argument must be known as soon as it is encountered.

这篇关于C ++ 0x允许decltype()函数签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆