在使用 constexpr 函数之前是否必须定义它们
Do constexpr functions have to be defined before they are used?
>见下面的代码,f()在下面定义 main 函数被认为是格式不正确的?谁能给我一个解释?
constexpr int f ();
void indirection ();
int main () {
constexpr int n = f (); // ill-formed, `int f ()` is not yet defined
indirection ();
}
constexpr int f () {
return 0;
}
void indirection () {
constexpr int n = f (); // ok
}
C++14 标准提供了以下代码片段(为方便起见,我缩短了代码片段):
constexpr void square(int &x); // OK: declaration
struct pixel {
int x;
int y;
constexpr pixel(int);
};
constexpr pixel::pixel(int a)
: x(a), y(x)
{ square(x); }
constexpr pixel small(2); // error: square not defined, so small(2)
// is not constant so constexpr not satisfied
constexpr void square(int &x) { // OK: definition
x *= x;
}
解决方案是将square
的定义移到small
声明之上。
从上面我们可以得出结论,可以转发声明constexpr
函数,但它们的定义必须在首次使用之前可用。
constexpr
某些东西必须在编译时,在每个使用它的点上知道。
这本质上与不能声明不完整类型的变量相同,即使该类型稍后在同一源中完全定义也是如此。
相关文章:
- 此递归模板类型定义是否有效C++?
- 虚拟成员函数的定义是否强制在同一转换单元中动态初始化静态数据成员?
- 越界成员函数定义是否需要一个完全限定的类名,直到全局范围
- C++标准是否定义了结构中成员函数的函数内定义是否必须具有静态链接?
- 带有"struct structname<..>"的模板定义是否正确?
- NTRUEncrypt:使用开源标准算法中的描述无法正确找到两个多项式的GCD,无法定义是否存在多边形的逆
- 定义重载C++函数模板的原型时,使用其名称引用以前的定义是否合法?
- 命名空间的定义是否可以跨越多个翻译单元
- 头文件中的类声明和定义是否在每个包含上编译
- 这个无括号的C预处理器定义是否安全
- char的实现定义是否会影响std::string
- 对内联函数有不同的定义是否是一种未定义的行为
- 同一字符串的多个#定义是否使用相同的常量字符串
- 根据编译时常量,使用相同的标识符 #define 或类型定义是否被认为是可接受的做法?
- 显式模板实例化定义是否也抑制隐式实例化
- 构造函数定义是否可以以 "class" 关键字为前缀?
- 类中的函数定义是否占用类大小的一部分?
- 名称空间作用域构造函数定义是否需要类限定的标识符
- i=i++;未定义.是否i=foo(i++)也未定义
- "volatile"的定义是否如此不稳定,还是 GCC 存在一些标准合规性问题?