C ++ 0x允许decltype()函数签名? [英] Does C++0x allow decltype() in function signature?
问题描述
这个问题显然假设我们不想使用这种类型的模板(无论什么原因)。
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屋!