在编译时获取std :: array中的元素数 [英] Getting the number of elements in std::array at compile time

查看:158
本文介绍了在编译时获取std :: array中的元素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是有效的C ++代码,为什么不?

Is the following a valid C++ code, and why not?

std::array<std::string, 42> a1;
std::array<int, a1.size()> a2;

它不能在GCC 4.8中编译(在C ++ 11模式下)。有一个简单但不起眼的解决方法:

It doesn't compile in GCC 4.8 (in C++11 mode). There is a simple but inelegant workaround:

std::array<std::string, 42> a1;
std::array<int, sizeof(a1)/sizeof(a1[0])> a2;

很明显,编译器可以找出std :: array中的元素数。为什么std :: array :: size()不是 constexpr static function?

So clearly the compiler can figure out the number of elements in std::array. Why std::array::size() is not a constexpr static function?

编辑:
我找到了另一个解决方法:

I have found another workaround:

std::array<std::string, 42> a1;
std::array<int, std::tuple_size<decltype(a1)>::value> a2;


推荐答案

array< T& :size() constexpr ,但是你不能以这种方式使用它,因为 a1 不是 constexpr 值。此外,它不能 constexpr ,因为 string 不是文字类型。

array<T>::size() is constexpr, but you can't use it in this way because a1 isn't a constexpr value. Additionally, it can't be constexpr because string isn't a literal type.

但是,你可以通过推导 size_t 模板参数来解决这个问题。示例:

However, you can work around this if you want, by deducing the size_t template parameter. Example:

#include <string>
#include <array>
#include <iostream>
using namespace std;

template<typename>
struct array_size;
template<typename T, size_t N>
struct array_size<array<T,N> > {
    static size_t const size = N;
};

array<string, 42> a1;
array<string, array_size<decltype(a1)>::size> a2;

int main() {
    cout << a2.size() << endl;
}

这篇关于在编译时获取std :: array中的元素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆