使用constexpr数组的元素与const数组的元素实例化模板
Using an element of a constexpr array vs a const array to instantiate a template
在回答一个问题时,我遇到了一个我无法解释的问题。
似乎有足够大的差异
constexpr size_t IntArray[2] = {1, 2};
和
const size_t IntArray[2] = {1, 2};
使得第一个模板的元素可以用来实例化模板,而第二个模板的元素不能。
演示差异的示例程序。
#include <cstddef>
template <size_t N> struct Foo {};
// Works fine
void test1()
{
constexpr size_t IntArray[2] = {1, 2};
const size_t i = IntArray[0];
Foo<i> f;
(void)f; // Remove unused f warning.
}
// Does not work
void test2()
{
const size_t IntArray[2] = {1, 2};
const size_t i = IntArray[0];
Foo<i> f;
(void)f; // Remove unused f warning.
}
int main()
{
return 0;
}
我使用g++ 4.9.2得到以下编译错误:
g++ -std=c++11 -Wall socc.cc -o socc
socc.cc: In function ‘void test2()’:
socc.cc:17:8: error: the value of ‘i’ is not usable in a constant expression
Foo<i> f;
^
socc.cc:16:17: note: ‘i’ was not initialized with a constant expression
const size_t i = IntArray[0];
^
socc.cc:17:9: error: the value of ‘i’ is not usable in a constant expression
Foo<i> f;
^
socc.cc:16:17: note: ‘i’ was not initialized with a constant expression
const size_t i = IntArray[0];
^
socc.cc:17:9: note: in template argument for type ‘long unsigned int’
Foo<i> f;
^
socc.cc:17:12: error: invalid type in declaration before ‘;’ token
Foo<i> f;
我的问题是为什么constexpr
数组工作,而不是const
数组?
constexpr
保证该值为编译时值,const
只禁止修改该值。
如果const变量是否是编译时值,则很容易标记单个const变量,对于c数组,它需要记住每个索引的信息。
即使我们能做到
const int two = 2;
constexpr int two_bis = two;
下面是不允许的
const size_t IntArray[2] = {1, bar()}; // with non constexpr bar()
constexpr size_t a = intArray[0]; // we might know that is compile time value
constexpr size_t b = intArray[1]; // but this one is clearly not
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int