如何转换std :: array< char,N>到char(&dest)[N]? [英] how convert std::array<char, N> to char (&dest)[N]?

查看:228
本文介绍了如何转换std :: array< char,N>到char(&dest)[N]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::array<char, N>传递给的方式是什么 这样的功能:

What is the way to pass std::array<char, N> to such function:

template<size_t N>
void safe_func(char (&dest)[N]);

?

我尝试这个:

#include <array>

template <size_t N> using SafeArray = char[N];

template <size_t N> void safe_func(char (&dest)[N]) {}

int main() {
  SafeArray<10> a1;
  safe_func(a1);
  std::array<char, 10> a2;
  safe_func(*static_cast<SafeArray<10> *>(static_cast<void *>(a2.data())));
}

它有效,但是我怀疑我的演员表可能出了点问题, 在其他编译器或平台上(我使用了gcc/linux/amd64), 我遇到了错误的参考?

It works, but I doubt, may be something wrong with my cast, and on other compiler or platform (I used gcc/linux/amd64), I faced with wrong reference?

推荐答案

一种方法:

template<class T, size_t N>
using c_array = T[N];

template<class T, size_t N>
c_array<T, N>& as_c_array(std::array<T, N>& a) {
    return reinterpret_cast<T(&)[N]>(*a.data());
}

int main() {
    std::array<int, 2> a;
    int(&b)[2] = as_c_array(a);
}

该标准要求std::array聚合,并且仅成员是T[N]std::array::data()返回的指针.由于集合的地址与其第一个成员的地址重合,因此不必严格要求调用和取消引用std::array::data()reinterpret_cast<T(&)[N]>(a)也可以正常工作.

The standard requires that std::array is an aggregate and it's only member is T[N], a pointer to which std::array::data() returns. As the address of an aggregate coincides with the address of its first member, calling and dereferencing std::array::data() is not strictly necessary, reinterpret_cast<T(&)[N]>(a) works as well.

std::array起源于 boost ,其唯一目的是为内置数组T[N]提供一个标准的容器接口(begin/end/size/empty/etc.),而没有别的,因此它没有任何开销,零成本的抽象.因此,虽然这样做可能会破坏boost::array<T, N>T[N](尽管编译器会假设boost::array<T, N>T[N]引用了不同的对象,但您可能这样做),但您基本上可以来回地转换boost::array<T, N>T[N].

std::array originated in boost, where its sole purpose was to provide a standard container interface (begin/end/size/empty/etc.) to built-in arrays T[N] and nothing else, so that it doesn't have any overhead, 0-cost abstraction. Hence, you can basically cast boost::array<T, N> and T[N] back and forth albeit possibly breaking aliasing rules by doing so (the compiler assumes that boost::array<T, N> and T[N] refer to different objects, so you need to know how to cope with that in your specific case).

该标准放弃了所有基本原理,并以非常微弱和模糊的术语表达了std::array的要求.因此人们想知道那里是否真的只有T[N]成员,而不是某些所谓的满足要求的地球外类型.

The standard dropped all the rationale and expressed the requirements of std::array in very weak and vague terms. So that people wonder whether it is truly only T[N] member there and not some allegedly extra-terrestrial type that satisfies the requirement.

这篇关于如何转换std :: array&lt; char,N&gt;到char(&dest)[N]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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