char和初始化列表

编程入门 行业动态 更新时间:2024-10-27 17:14:30
本文介绍了char和初始化列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想通过初始化列表一个可变参数模板将一些数字字节值传递到数组。这是可能吗?

I'd like to pass some numeric byte values via an initializer list a variadic template into an array. Is that possible?

template < int N > struct a { char s[N]; template < typename ... A > a (A ... _a) : s {_a...} {} }; int main () { // g++-4.5: error: narrowing conversion of »_a#0« from »int« to »char« inside { } a < 3 > x { 1, 2, 3 }; }

我可以想到的是

  • 使用八进制表示法,'\001'等或
  • 来投射每个值。

但两者都不令人满意。

推荐答案

注意:除非您向类添加了功能,否则这些都是不必要的,因此它不再是聚合。 (例如,其他构造函数,私有成员,基类等)解决问题中的代码的直接方法是简单地删除构造函数。所以,让我们假设有更多的东西。

NOTE: All of this is unnecessary unless you have added functionality to the class so it's no longer an aggregate. (For example, other constructors, private members, a base class, etc.) The immediate way to fix the code in the question is simply to remove the constructor. So, let's assume there's something more to it.

我见过一些人想做这样的事情。它看起来很丑陋,处理转换语义,并试图人为地重新创建一个通常的函数调用的功能。

I've seen some people trying to do things like this. It seems ugly, dealing with conversion semantics and trying to artificially re-create the functionality of a usual function call.

这里是一个策略创建一个数组类,正确的构造函数。

Here is a strategy to create an array class that simply has the right constructor in the first place.

模板别名将通过隐藏 :: type 丑陋,但它不在GCC。

Template aliasing would put the icing on the cake by hiding the ::type ugliness, but it's not in GCC yet.

template< typename ... NT > struct var_ctor_array { enum { size_e = 0 }; // only used for zero size case }; template< typename T, typename ... NT > struct var_ctor_array< T, NT ... > { enum { size_e = 1 + sizeof...( NT ) }; T st[ size_e ]; var_ctor_array( T elem0, NT ... elemN ) : st { elem0, elemN ... } {} }; template< typename T, size_t N, typename ... NT > struct gen_var_ctor_array { typedef typename gen_var_ctor_array< T, N-1, T, NT ... >::type type; }; template< typename T, typename ... NT > struct gen_var_ctor_array< T, 0, NT ... > { typedef var_ctor_array< NT ... > type; }; int main() { // usage gen_var_ctor_array< char, 5 >::type five( 1, 2, 3, 4, 5 ); }

更多推荐

char和初始化列表

本文发布于:2023-07-30 11:05:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1248834.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   列表   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!