在模板中隐式使用字符串的长度 [英] Take the length of a string implicitly in templates

查看:133
本文介绍了在模板中隐式使用字符串的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,假设我有一个神奇的模板,它接受一个 char 数组并将其转换为模板参数列表。例如:thing被翻译为列表<'t','h','i','n','g' ;

Ok, suppose I have this magic template that takes a char array and turns it into a template parameter list. For example: "thing" is translated to list<'t','h','i','n','g'>:

template<const char*, size_t>
ArrayToList;

您可以这样使用:

constexpr char string[] = "this is a test";
typedef ArrayToList<string,14> list;

有什么办法以某种方式检测字符串长度隐式,所以我需要做的是: / p>

Is there any way to somehow detect the string length implicitly so that all I have to do is:

typedef ArrayToList<string> list;


推荐答案

不幸的是,它不能做:
你想有一个非类型模板参数(字符串)。在语法上,指定非类型模板参数的唯一方法是声明它的类型,但是,类型取决于字符串本身的长度,并且需要两个模板参数(length和string),或者如果将string to const char * ,该字符串的长度在参数中丢失。

Unfortunately, it can't be done: You would like to have a non-type template parameter (the string). Syntactically speaking, the only way to specify a non-type template parameter is to declare its type, however, either the type depends on the length of the string itself and you need two template parameters (length and string), or if you convert the string to const char *, the length of the string is lost in the parameter.

捕获非类型模板参数,其类型本身需要一个模板参数,以防止强制使用这些额外模板参数的语法,例如您的情况。

There are proposals to allow the capture of non-type template parameters whose type itself requires a template parameter to prevent forcing the syntax of those extra template arguments, like in your case.

一个建议:如果你把参数的顺序还原为 ArrayToList ,我想你可以通过捕获non-type参数的长度来简化代码,如下:

One recommendation: If you revert the order of the arguments to ArrayToList, I think you can simplify the code by capturing the non-type parameter with its length, as here:

template<char...> struct list {};

// just a declaration
template<char, typename> struct add_to_list;

// specializes for the case of a list of chars, to insert v
template<char v, char... pack> struct add_to_list<v, list<pack...>> {
  using type = list<v, pack...>;
};

// captures str[length - rindex] into the head of the list
template<unsigned rindex, unsigned length, const char str[length]>
  struct to_list {
    using type = typename add_to_list<
      str[length - rindex],
      typename to_list<rindex - 1, length, str>::type
    >::type;
  };

// base of the recursion
template<unsigned length, const char str[length]>
  struct to_list<1, length, str> {
    using type = list<>;
  };

template<unsigned string_length, const char str[string_length]>
  using ArrayToList =
    typename to_list<string_length, string_length, str>::type;


// now, an example
constexpr char str[] = "hello";


template<typename> struct show_type_in_error;
show_type_in_error<ArrayToList<sizeof(str), str>> error;

这篇关于在模板中隐式使用字符串的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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