为什么我不能在 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/