c++ - 用于创建 fixed_string 并包装 std::array 的 Constexpr 构造函数
问题描述
我正在尝试创建一个 constexpr fixed_string 类,但构造函数能够将const char*
和转换const char(&)[L]
为std::array<char, Length>
.
#include <array>
#include <string>
#include <iostream>
template <typename char_type, std::size_t Length>
struct fixed_string
{
constexpr fixed_string(const char_type* value)
:
mData{reinterpret_cast<char_type[std::char_traits<const char_type>::length(value)]>(value)}
{
}
template <std::size_t L>
constexpr fixed_string(const char_type (&value)[L])
:
mData{{value}}
{
static_assert(L <= Length);
}
std::array<char_type, Length> mData;
};
template <typename char_type, std::size_t L>
std::ostream& operator<<(std::ostream& os, fixed_string<char_type, L> s)
{
for (auto c : s.mData)
os << c;
return os;
}
int main() {
constexpr char hello[] = "hello";
std::cout << fixed_string<const char, 6>{hello} << std::endl;
std::cout << fixed_string<const char, 6>{"hello"} << std::endl;
return 0;
}
我的两种构造方法目前都不正确。错误消息包括:
10:15: error: invalid cast from type 'const char*' to type 'char [(<anonymous> + 1)]'
10 | mData{reinterpret_cast<char_type[std::char_traits<const char_type>::length(value)]>(value)}
17:22: error: invalid conversion from 'const char*' to 'char' [-fpermissive]
17 | mData{{value}}
我正在使用std::char_traits<char>::length
它,因为它是 constexpr。也许这可能是不安全的,strlen(value) > Length
但希望 std::array 的构造可以解决这个问题?
我知道我可以在运行时使用 std::copy 创建一个 fixed_string 类。我希望我可以改进它以使其成为 constexpr。我一直在用 gcc10.2 --std=c++17 编译。
任何帮助将不胜感激。
编辑:添加模板 char_type 以显示我不一定关心 char 的类型。
解决方案
推荐阅读
- reactjs - 如何在打字稿/反应中创建一个基本的观察者类?
- c++ - 用数据填充未指定大小的数组
- javascript - 如何正确停止动画中间
- enums - 实现自定义错误枚举时,特征绑定 io::Error: Clone is not满足
- javascript - JavaScript 中的事件计时
- r - 在 80 个依赖结果的同一列表上运行多个自变量的回归模型的最有效方法是什么?
- bash - 更快地运行 bash 脚本
- python - 如何从 Ubuntu 19.10 卸载 python 3.7?
- keras - 每个activation_9n 的重复错误(例如:activation_9、..activation_45.. 等)
- javascript - 如何使用条件将选择的行从表 A 复制到表 B?