如何解决Constexpr 构造函数来创建 fixed_string 并包装 std::array<char, L>
我正在尝试创建一个 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 以表明我不一定关心字符的类型。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。