考虑以下MWE (https://godbolt.org/g/aydjpW):
#include <cstdlib>
#include <array>
template<size_t N> constexpr std::array<void*, N> empty_array{};我的目标是拥有一个大小为N的数组,其中每个元素都是默认初始化的(在这种情况下,nullptr)。g++ 5.4.0与-std=c++11一起抱怨
变量模板仅适用于-std=c++14或-std=gnu++14
我不明白为什么。根据http://en.cppreference.com/w/cpp/container/array的说法,array<T, N>存在于C++11和隐式声明的构造函数之后
按照聚合初始化规则初始化数组。
按照initialization上对聚合初始化的描述的链接,它指出
如果初始化子句的数量小于成员数或初始化程序列表完全为空,则其余成员为值初始化。
因此,我的假设是,我上面的代码是有效的C++11。在这里,我遗漏了哪些变量模板,这将需要C++14?
发布于 2018-02-07 13:07:56
要声明包含5个元素的array:
constexpr std::array<void*, 5> empty_array{};要声明包含10个元素的array:
constexpr std::array<void*, 10> empty_array{};要声明N元素的数组(其中N不是固定的),您需要使用一个模板,该模板可以对N的不同值进行实例化:
// A variable of type std::array<void*, N> where N is not fixed yet:
template<size_t N> constexpr std::array<void*, N> empty_array{};
// Then given a function like this:
void do_something(const std::array<void*, 5>&);
// You use the variable like this, by giving the value of N:
void some_function() {
do_something(empty_array<5>);
}但是这是一个可变模板,它是C++14中的一个新特性,您不能在C++11中这样做,所以您得到了编译器错误。
要么使用C++14,要么执行以下操作:
// An alias template defining a _type_ of array with no fixed N:
template<std::size_t N>
using voidptr_array = std::array<void*, N>;
constexpr voidptr_array<5> empty_array_of_5{};
constexpr voidptr_array<10> empty_array_of_10{};
void do_something(const std::array<void*, 5>&);
void some_function() {
do_something(empty_array_of_5);
}此别名模板定义了以N作为参数的类型,而不是以N作为参数的变量。您仍然需要定义该类型的变量,如empty_array_of_5和empty_array_of_10。
发布于 2018-02-07 13:01:10
在C++14中引入了可变模板,请参阅template
https://stackoverflow.com/questions/48664461
复制相似问题