在 C++ 中,命名参数的范围是否包括其默认值的表达式?
In C++, does the scope of a named parameter include the expression for its default value?
示例:这是合法的 C++14 吗?
#include <iostream>
static int d() {
return 42;
}
static int e(int d = d()) {
return d;
}
int main() {
std::cout << e() << " " << e(-1) << std::endl;
}
g++ 5.4 with -std=c++14
喜欢它,但是 clang++ 3.8 with -std=c++14
抱怨:
samename.cxx:3:23: error: called object type 'int' is not a function or function pointer
static int e(int d = d()) {return d;}
~^
似乎不合法:请参阅 C++14 规范 (section 3.3.2 - Point of declaration)。
int x = 5;
{ int x = x; } // second x is initialized with its own undetermined state
{ int x[x]; } // declares an array with 5 elements, since the declaration of
// second x is not complete when the first x is used
在你的例子中,d
的声明是完整的,所以当你使用 d()
时,你指的是变量,而不是函数。
The point of declaration for a name is immediately after its complete
declarator and before its initializer (if any), except as noted below.
Example:
unsigned char x = 12;
{ unsigned char x = x; }
Here the second x
is initialized with its own (indeterminate) value.
Clang 与标准的这一部分一致。 GCC 似乎只在 {block}
.
中应用它
鉴于:
constexpr int d() {return 42;}
以下在 Clang 中失败,但在 GCC 中有效:
static int e(int d = d()) {return d;}
// This ^^d should refer to the new name that shadows ::d()
以下在 Clang 和 GCC 中都失败了:
void func(){
int d = d();
// ^^d here refers to the new name that shadowed ::d();
}
示例:这是合法的 C++14 吗?
#include <iostream>
static int d() {
return 42;
}
static int e(int d = d()) {
return d;
}
int main() {
std::cout << e() << " " << e(-1) << std::endl;
}
g++ 5.4 with -std=c++14
喜欢它,但是 clang++ 3.8 with -std=c++14
抱怨:
samename.cxx:3:23: error: called object type 'int' is not a function or function pointer
static int e(int d = d()) {return d;}
~^
似乎不合法:请参阅 C++14 规范 (section 3.3.2 - Point of declaration)。
int x = 5;
{ int x = x; } // second x is initialized with its own undetermined state
{ int x[x]; } // declares an array with 5 elements, since the declaration of
// second x is not complete when the first x is used
在你的例子中,d
的声明是完整的,所以当你使用 d()
时,你指的是变量,而不是函数。
The point of declaration for a name is immediately after its complete declarator and before its initializer (if any), except as noted below.
Example:
unsigned char x = 12; { unsigned char x = x; }
Here the second
x
is initialized with its own (indeterminate) value.
Clang 与标准的这一部分一致。 GCC 似乎只在 {block}
.
鉴于:
constexpr int d() {return 42;}
以下在 Clang 中失败,但在 GCC 中有效:
static int e(int d = d()) {return d;}
// This ^^d should refer to the new name that shadows ::d()
以下在 Clang 和 GCC 中都失败了:
void func(){
int d = d();
// ^^d here refers to the new name that shadowed ::d();
}