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

标签 c++ tuples variadic-templates c-strings

为什么我不能在 std::pair 中分配字符数组?或 boost::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++ 在元组中存储原始字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58592285/

相关文章:

C++每个派生类中的不同常量成员,如何移动函数以消除访问中的重复?

c++ - Gaffer游戏时间步长:std::chrono实现

c++ - 开发 Cpp "make.exe"错误代码 = 0xc00000fd

Python - 将元组列表转换为字符串

c++ - 将 std::tuple 转换为 std::array C++11

c++ - 隐藏在派生类中的虚函数

tuples - 域和元组关系演算

c++ - 我如何获得指向已推导的模板函数的指针?

c++ - gcc 的显式实例化失败 - 为什么?

c++ - 连续数组多维表示的快速元素访问