gpt4 book ai didi

c++ - 为什么 boost::any 不保存字符串文字?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:19:23 27 4
gpt4 key购买 nike

#include <boost/any.hpp>
#include <list>
#include <string>
#include <vector>

struct _time_t {
int month;
int year;
};


int main()
{
std::string str = "hahastr";
_time_t t;
std::vector<boost::any> objVec;
objVec.push_back(1);
char* pstr = "haha";
//boost::any charArr = "haha"; not compile
//objVec.push_back("haha"); not compile
objVec.push_back(pstr);
objVec.push_back(str);
objVec.push_back(t);
return 0;
};

注释的代码行不编译,为什么?我认为字符串文字在大多数情况下可以充当 char*,这是相关的右值和左值吗?

错误信息:test_boost_any.cc

D:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\INCLUDE\xlocale(336) : wa
rning C4530: C++ exception handler used, but unwind semantics are not enabled. S
pecify /EHsc
e:\projects\framework\boost_1_53_0\boost/any.hpp(122) : error C2536: 'boost::any
::holder<ValueType>::boost::any::holder<ValueType>::held' : cannot specify expli
cit initializer for arrays
with
[
ValueType=const char [5]
]
e:\projects\framework\boost_1_53_0\boost/any.hpp(139) : see declaration
of 'boost::any::holder<ValueType>::held'
with
[
ValueType=const char [5]
]
e:\projects\framework\boost_1_53_0\boost/any.hpp(120) : while compiling
class template member function 'boost::any::holder<ValueType>::holder(ValueType
(&))'
with
[
ValueType=const char [5]
]
e:\projects\framework\boost_1_53_0\boost/any.hpp(47) : see reference to
function template instantiation 'boost::any::holder<ValueType>::holder(ValueType
(&))' being compiled
with
[
ValueType=const char [5]
]
e:\projects\framework\boost_1_53_0\boost/any.hpp(46) : see reference to
class template instantiation 'boost::any::holder<ValueType>' being compiled
with
[
ValueType=const char [5]
]
test_boost_any.cc(19) : see reference to function template instantiation
'boost::any::any<const char[5]>(ValueType (&))' being compiled
with
[
ValueType=const char [5]
]

最佳答案

string-literal 不是指针,它是 N const char 数组,在您的情况下,因为 boost::any 构造函数接收 T (推导为 char[5],而不是 const char*,数组到指针的转换不能在这里工作),但是你不能通过另一个数组来初始化数组initializer-list 中的数组。

关于c++ - 为什么 boost::any 不保存字符串文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19949887/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com