显然,这个问题假设我们不想为此类型使用模板(无论出于何种原因)。

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
};

问题是:在C++ 0x中是否允许 1.和2.

最佳答案

您要做的就是在使用mPrice之前声明mLabeldecltype:

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可以很好地进行编译。

编辑重点是,编译器必须能够在第一次通过时解析函数声明。可以在解析成员声明之后编译成员函数的主体,但是成员声明本身必须立即可理解-否则,不良的编译器将从何处开始?

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

10-02 02:44