c++ - 从 C 字符串构造 boost::type_erasure::any 但存储为 std::string

标签 c++ string c++11 boost boost-type-erasure

是否可以声明 boost::type_erasure::any以从字符串文字或 char const* 构造和分配的方式自动将字符串复制到 std::string 并将其存储在 boost::type_erasure::任何对象?

默认情况下,boost::type_erasure::any 只存储字符串指针。

目的是避免当我的 any 类型的用户分配一个字符串指针给它时,假设将进行复制(如 std::string 会),然后字符串的生命周期在我的 any 被读取之前结束,导致崩溃。

例子:

#include <boost/type_erasure/operators.hpp>
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/type_erasure/relaxed.hpp>
#include <boost/mpl/vector.hpp>

#include <iostream>

namespace te = boost::type_erasure;

using my_any = te::any< boost::mpl::vector<
    te::copy_constructible<>,
    te::destructible<>,
    te::typeid_<>,
    te::relaxed
    /* I believe some changes here would do the trick */
    >>;

using namespace std;

int main()
{
    // Store an std::string by explicitly calling string constructor.
    my_any a = string("abc");

    // The following should copy-construct an std::string too but it just stores
    // the string pointer.
    my_any b = "abc";

    // Works as expected.
    cout << te::any_cast<string>( a ) << endl;

    // This crashes because the underlying type of b is not std::string.
    // With some changes to the my_any type this shouldn't crash anymore.
    cout << te::any_cast<string>( b ) << endl;
}

Live Demo.

最佳答案

不,any 存储任何内容。 const char* 是任何东西。

请注意,"hello"sstd::string 类型的文字。

关于c++ - 从 C 字符串构造 boost::type_erasure::any 但存储为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42837888/

相关文章:

javascript - 如果字符串长于给定参数,则在字符串末尾添加句点

字符串字面值未被解释为字符串类型

c++ - 是否需要 nullptr_t 类型的对象?

C++ sscanf_s 值不正确

c++ - 程序化 QGraphicsView 滚动未正确更新

c - 在 C 中将 strncat 与 char 数组元素一起使用

C++11 无锁序列号生成器安全吗?

c++ - 这段代码中的 begin() 指针是如何创建的?

c++ - c++中引用变量的内存?

c++ - 我如何在继承构造函数上做正确的 SFINAE?