Dec 14, 2016

[c++][c++17] Declaring non-type template parameters with auto

Declaring non-type template parameters with auto
cppref: aggregate_initialization
int i;
int&& f();
auto            x2a(i);          // decltype(x2a) is int
decltype(auto)  x2d(i);          // decltype(x2d) is int
auto            x3a = i;         // decltype(x3a) is int
decltype(auto)  x3d = i;         // decltype(x3d) is int
auto            x4a = (i);       // decltype(x4a) is int
decltype(auto)  x4d = (i);       // decltype(x4d) is int&
auto            x5a = f();       // decltype(x5a) is int
decltype(auto)  x5d = f();       // decltype(x5d) is int&&
auto            x6a = { 1, 2 };  // decltype(x6a) is std::initializer_list<int>
decltype(auto)  x6d = { 1, 2 };  // error, { 1, 2 } is not an expression
auto*           x7a = &i;        // decltype(x7a) is int*
decltype(auto)* x7d = &i;        // error, declared type is not plain decltype(auto);

int foo(int x) {
    return x;
}
// FAIL TO COMPILE.
// Function id-expressions do not decay to pointers when evaluating with decltype
decltype(auto) v = foo; 


int foo(int x) {
    return x;
}
// int (&) (int)
// Parenthesized function symbol expressions are deduced as a reference to
// the function.
decltype(auto) v = (foo);


// FAIL TO COMPILE
// Lambdas cannot capture references. 
// When y is captured, it captures the referred-to value x. 
// Because captures are const, the captured value ends up as const int. 
// However, decltype(auto) sees the symbol y’s declaration as an int& and deduces the type of v as int&.
// Compilation fails on discarding the const qualifier when trying to assign a const int to an int&.
int x;
int& y = x;
[=] () {
    decltype(auto) v = y;
}();

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.