问题描述
在回答,我遇到了一个我无法解释的问题。
While answering a question, I ran into an issue that I couldn't explain.
似乎有足够大的差异
constexpr size_t IntArray[2] = {1, 2};
和
const size_t IntArray[2] = {1, 2};
第一个的元素可用于实例化模板,但不能用于第二个的元素。
that the elements of the first can be used to instantiate a template but not the elements of the second.
演示差异的示例程序。
#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时遇到以下编译错误。
I get the following compiler error using 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
数组?
My question is why does the constexpr
array work but not the const
array?
推荐答案
constexpr
确保该值是编译时的值,而 const
则禁止修改该值。
constexpr
ensures that value is compile time value whereas const
forbids only to modify the value.
然而,很容易标记单个const变量,如果它是一个编译时值,
为C阵列,它将需要记住每个索引的信息。
Whereas it is easily to mark single const variable if it is a compile time value or not,for C-array, it would require to remember that information for each index.
即使我们可以做
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
这篇关于使用constexpr数组的元素与const数组来实例化模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!