c++ - 在模板中隐式获取字符串的长度

标签 c++ templates constexpr

好吧,假设我有这个魔法template这需要 char数组并将其转换为模板参数列表。例如:"thing"翻译成list<'t','h','i','n','g'> :

template<const char*, size_t>
ArrayToList;

你可以这样使用它:

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

有什么方法可以隐式检测字符串长度,这样我所要做的就是:

typedef ArrayToList<string> list;

最佳答案

不幸的是,它无法完成: 您想要一个非类型模板参数(字符串)。从句法上讲,指定非类型模板参数的唯一方法是声明其类型,但是,类型取决于字符串本身的长度并且您需要两个模板参数(长度和字符串),或者如果您将string to const char *,参数中丢失了字符串的长度。

有人提议允许捕获非类型模板参数,其类型本身需要一个模板参数,以防止强制使用这些额外模板参数的语法,就像您的情况一样。

我在 try catch 指向成员的指针时遇到了同样的问题,有必要也说明什么是聚合。

一个建议:如果将参数的顺序还原为 ArrayToList,我认为您可以通过捕获非类型参数及其长度来简化代码,如下所示:

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;

关于c++ - 在模板中隐式获取字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37892646/

相关文章:

c++ - 三角函数的模板重载

c++ - 抛出 constexpr 函数

c++ - OPENCV CUDA -- getCudaEnabledDeviceCount 返回 0

c++ - 有没有一种方法可以机械地识别哪些操作对移出的对象是安全的?

c++ - 如何一次专门化多种类型的方法

javascript - Meteor 中的 Template.created 和 Template.onCreated 有什么区别?

c++ - 如何在 Makefile 中创建静态隐式规则?

c++ - 如何引用二维数组中的对象?

带有 lambda 表达式的 constexpr 的 C++ 用法

c++ - constexpr const 与 constexpr 变量?