Consider the next code
struct X
{
X(float) {}
};
int const x = 3;
X f(float(x));
Should a standard C++ compiler parse the last line as a function declaration with type X (*)(float)
or as making an instance of X
by calling X::X(float(3))
?
That is a function declaration. Paragraph 8.2/1 of the C++11 Standard explains this:
The ambiguity arising from the similarity between a function-style cast and a declaration mentioned in 6.8 can also occur in the context of a declaration. In that context, the choice is between a function declaration with a redundant set of parentheses around a parameter name and an object declaration with a function-style cast as the initializer. Just as for the ambiguities mentioned in 6.8, the resolution is to consider any construct that could possibly be a declaration a declaration.
The Standard also provides an example:
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
}
The declaration in your example declares a function that takes a float
and returns an X
, as proved by the (non-firing) static assertion in the following program (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, "!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With