C++ 在元组中存储原始字符数组

C++ storing raw character array in tuple

为什么我不能在 std::pairboost::tuple 中分配字符数组?

typedef std::pair<int, char [5]> tuple_type;
tuple_type(5, "abcd");

以上产生了以下错误。

error: no matching function for call to ‘std::pair<int, char [5]>::pair(int, const char [5])’
   51 |     tuple_type(5, "abcd");

即使我使用 std::pair<int, const char [5]> 错误仍然存​​在

error: no matching function for call to ‘std::pair<int, const char [5]>::pair(int, const char [5])’

唯一的解决方案是使用 const char*std::string 但在我的实际问题中,我将一组可变参数打包到一个元组中。

template <typename Ret, typename CallableT, typename... Args>
struct returned_: public Ret{
    typedef boost::hana::tuple<Args...> tuple_type;
    tuple_type _tuple;
    const CallableT& _call;

    returned_(const CallableT& call, const Args&... args): _call(call), _tuple(args...), Ret(_tuple){}
    // ...
};

因此,除非用户代码强制转换为 const char* 或包含在 std::string 中,否则模板 returned_ 将产生编译时错误。不强制用户不传递 C 字符串文字的解决方案是什么?

在参数列表表达式中

tuple_type(5, "abcd");

字符串文字 "abcd" 隐式转换为类型 const char *。并且数组没有赋值运算符,而且当指针用作初始值设定项时。

C 数组不可复制,您可能希望将其包装成可复制的结构 std::array

正如我在问题中提到的,我不想强​​制用户仅传递 std::string 或强制转换为 const char*。我正朝着@NathanOliver

指出的方向前进
template <typename T>
struct trans{
    typedef typename std::decay<T>::type type;
};
template <int N>
struct trans<char[N]>{
    typedef const char* type;
};

template <typename T>
using trans_t = typename trans<T>::type;

以上模板会将 char[N] 转换为 const char*

template <typename Ret, typename CallableT, typename... Args>
struct returned_: public Ret{
    typedef boost::hana::tuple<trans_t<Args>...> tuple_type; // trans_t will convert char[N] to const char*
    tuple_type _tuple;
    const CallableT& _call;

    returned_(const CallableT& call, const Args&... args): _call(call), _tuple(args...), Ret(_tuple){}
    // ...
};