Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function or instance declaration? [duplicate]

Tags:

c++

c++11

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

like image 950
a.lasram Avatar asked Jun 26 '13 21:06

a.lasram


1 Answers

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, "!");
}
like image 59
Andy Prowl Avatar answered Oct 17 '22 18:10

Andy Prowl