4
#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* として機能すると思いますが、これは r-value と l-rvalue に関連していますか?

エラー メッセージ: 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]
        ]
4

5 に答える 5

4

string-literal はポインターではありませんarray of N const char。あなたの場合、boost::anyコンストラクターが受信するためTです (配列からポインターへの変換はここでは機能しませんchar[5]) 。const char*initializer-list

于 2013-11-13T09:25:13.157 に答える
2

Boost.any の値は、割り当てるために有効である必要があります (の要件ValueType)。ただし、文字列リテラルは配列であり、C++ では配列を割り当てることができません。

const char *必要に応じて、リテラルを a にキャストできます。

于 2013-11-13T09:36:39.940 に答える
2

ここでのCの厄介な配列セマンティクスの最も簡単な回避策は次のとおりです

boost::any charArr = +"haha"; 

+を使用して char 配列を暗黙的に減衰させることに注意してください。const char*

他の人は、配列値のセマンティクスの問題を説明しています

于 2013-11-13T10:30:34.733 に答える
0

この問題の単純化されたバージョン:

template <typename T>
class Array
{
    public:
        Array(T value) : value_(value) {}  
    private:
        T value_;
};

int main()
{
    int a[5] = {1,2,3,4,5};
    Array<int[5]> arr = a;
    return 0;
}
于 2013-11-13T14:27:44.573 に答える