C++ 0x是否允许函数签名中的decltype()?

Kla*_*aim 8 c++ c++11

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

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
};
Run Code Online (Sandbox Code Playgroud)

问题是:在C++ 0x中是1.和2.允许和可能(甚至是特定的)?

peo*_*oro 8

是的,但使用不同的语法:

auto price() -> decltype(mPrice) { return mPrice; }
auto price() -> decltype(mPrice) { return mPrice; }
Run Code Online (Sandbox Code Playgroud)

更一般:

auto function( ... ) -> decltype(EXPRESSION) ...
Run Code Online (Sandbox Code Playgroud)

function 返回类型将是 EXPRESSION


编辑

关于案例1我不确定.我不认为是有效的,因为mPrice在这种情况下不要认为这是一个有效的表达式:你使用的是非静态函数member(Product::mPrime)而没有对象.

我的猜测是,如果它mPrime是一个静态成员,它将起作用.


Ton*_*nyK 7

您所要做的就是声明mPricemLabel 使用之前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.
};
Run Code Online (Sandbox Code Playgroud)

这在g ++ 4.4下用-std = c ++ 0x编译得很好.

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

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