简体   繁体   English

函数模板,将字符串文字转换为std :: array

[英]Function template to turn a string literal into a std::array

Is it possible to have a function template that'll take a "string literal" and return a std::array<char,N> equivalent to 是否可以有一个函数模板,该函数模板将使用"string literal"并返回与以下内容等效的std::array<char,N>

 char array[] = "string literal";

?

I'm wrapping POSIX APIs and I'd like to have a mkstemp function template that'll take a string literal and return 我包装了POSIX API,我想拥有一个mkstemp函数模板,该模板将接受字符串文字并返回

std::pair<
 ModifiedLiteral //template turned into actual name (probably in std::array)
,FileFd_RW       //My fd wrapper
>;

without using the heap. 不使用堆。

Yes, you can: 是的你可以:

#include <array>
#include <functional>
#include <cstddef>

template <std::size_t N> std::array<char, N> parse_literal(const char (&lit)[N]) {
  std::array<char, N> arr;
  std::copy(lit, lit + N, arr.begin());

  return arr;
}

void foo() {
  parse_literal("This is my rifle, this is my gun");
}

If your compiler supports C++14 you could use std::index_sequence to craft a machinery that would copy the string literal in compile time: 如果您的编译器支持C ++ 14,则可以使用std::index_sequencestd::index_sequence一种在编译时复制字符串文字的机制:

template<std::size_t N, std::size_t... I>
constexpr 
std::array<char, N>
a2t_impl(char const (&str)[N], std::index_sequence<I...>) {
    return {str[I]...};
}

template<std::size_t N, typename Indices = std::make_index_sequence<N>>
constexpr 
std::array<char, N>
a2t(char const (&str)[N]) {
    return a2t_impl(str, Indices());
}

template<std::size_t N>
constexpr 
std::array<char, N> 
stringtoarray(char const (&str)[N]) {
  return a2t(str);
}

Live Demo 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM