【问题标题】:function or instance declaration? [duplicate]函数或实例声明? [复制]
【发布时间】:2013-06-26 21:44:07
【问题描述】:

考虑下一个代码

struct X
{
    X(float) {}
};

int const x = 3;

X f(float(x));

标准 C++ 编译器应该将最后一行解析为类型为 X (*)(float) 的函数声明,还是通过调用 X::X(float(3)) 生成 X 的实例?

【问题讨论】:

  • 这是一个声明
  • @Mahmoud Al-Qudsi - 你完全正确。这是相关的

标签: c++ c++11


【解决方案1】:

这是一个函数声明。 C++11 标准的第 8.2/1 段解释了这一点:

由于函数样式转换和 6.8 中提到的声明之间的相似性而产生的歧义 也可以在声明的上下文中出现。在这种情况下,选择是在函数声明之间 在参数名称和具有函数样式的对象声明周围有一组冗余括号 强制转换为初始值设定项。正如 6.8 中提到的歧义一样,解决方案是考虑任何构造 这可能是一个声明一个声明

该标准还提供了一个示例:

struct S {
    S(int);
};
void foo(double a) {
S w(int(a)); // function declaration     <=== Your example
S x(int()); // function declaration
S y((int)a); // object declaration
S z = int(a); // object declaration
}

您的示例中的声明声明了一个函数,该函数接受 float 并返回 X,正如以下程序 (live example) 中的(非触发)静态断言所证明的那样:

#include <type_traits>

struct X
{
    X(float) {}
};

int const x = 3;

X f(float(x));

int main()
{
    static_assert(std::is_same<decltype(f), X(float)>::value, "!");
}

【讨论】:

  • 你能解释一下这是什么类型的函数,这个例子是
  • @aaronman:我扩展了答案
  • 那么x 会发生什么,因为float(x) 不是正确的类型,在函数声明中你应该有一个类型
  • @aaronman: x 被认为是函数ffloat 参数的名称。写f(float(x)) 只是在函数声明中写f(float x) 的另一种方式(我认为这来自C,但我不确定)。
猜你喜欢
  • 2012-07-15
  • 1970-01-01
  • 2013-05-23
  • 2023-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-17
相关资源
最近更新 更多