5

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)) ?

a.lasram
  • 4,371
  • 1
  • 16
  • 24

1 Answers1

8

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, "!");
}
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • could you explain what type of function this declares, the example that is – aaronman Jun 26 '13 at 21:55
  • @aaronman: I expanded the answer – Andy Prowl Jun 26 '13 at 21:59
  • so what happens to the `x` because `float(x)` is not a type right, in a function declaration you should have a type – aaronman Jun 26 '13 at 22:03
  • @aaronman: `x` is considered as the name of the `float` argument of the function `f`. Writing `f(float(x))` is just an alternative way of writing `f(float x)` in a function declaration (I think this comes from C, but I'm not sure). – Andy Prowl Jun 26 '13 at 22:05