,c++,string,constexpr"/>

首页 > 解决方案 > 用于创建 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 的类型。

标签: c++stringconstexpr

解决方案


推荐阅读