首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从C字符串构造boost::type_erasure::any,但存储为std::string

从C字符串构造boost::type_erasure::any,但存储为std::string
EN

Stack Overflow用户
提问于 2017-03-16 23:09:31
回答 2查看 134关注 0票数 1

是否可以这样声明boost::type_erasure::any:从字符串文字或char const*构造和赋值会自动将字符串复制到std::string中,并将其存储在boost::type_erasure::any对象中?

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

这样做的目的是为了避免当我的any类型的用户将字符串指针分配给它时的错误来源,假设将进行复制(就像std::string一样),然后字符串的生命周期在我的any被读取之前结束,从而导致崩溃。

示例:

代码语言:javascript
复制
#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.

EN

回答 2

Stack Overflow用户

发布于 2017-03-17 01:21:59

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

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

票数 0
EN

Stack Overflow用户

发布于 2017-03-17 05:21:43

我发布了我自己问题的答案,希望在不使原始问题变得过于冗长的情况下阐明boost::type_erasure::any的预期用途。

此答案显示了一种可能的解决方法,方法是将boost::type_erasure::any隐藏在另一个类的接口后面,并为所有可转换为std::string的类型提供setter方法的重载。此重载负责将字符指针和字符数组转换为std::string

我认为一个额外的重载并不是那么糟糕,但理想情况下,我希望避免这种样板,并使any类型知道如何转换C字符串。这让我们回到了我的original question

代码语言:javascript
复制
#include <iostream>
#include <unordered_map>
#include <string>
#include <type_traits>

#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>

namespace te = boost::type_erasure;

// A class to store attributes of any type by name.
class Attributes
{
public:
    using Key = std::string;

    // A type that can store any value (similar to std::any).
    using AnyValue = te::any< boost::mpl::vector<
        te::copy_constructible<>,
        te::destructible<>,
        te::typeid_<>,
        te::relaxed
        >>;

    // Overload for all types that ain't strings.
    template< typename T >
        std::enable_if_t< !std::is_convertible<T, std::string>::value, 
    void > SetAttr( Key const& name, T&& value )
    {
        m_attr.insert_or_assign( name, std::forward<T>( value ) );
    }

    // Convert to std::string for all convertible types
    // (char pointer and char array included).
    template< typename T >
        std::enable_if_t< std::is_convertible<T, std::string>::value, 
    void > SetAttr( Key const& name, T&& value )
    {
        m_attr.insert_or_assign( name, std::string( std::forward<T>( value ) ) );
    }

    template< typename T >
    T GetAttr( Key const& name ) const 
    { 
        return te::any_cast<T>( m_attr.at( name ) ); 
    }

private:
    std::unordered_map<Key, AnyValue> m_attr;
};

以下示例说明了如何通过Attributes::GetAttr<std::string>()将不同类型的字符串传递给Attributes::SetAttr()并进行常规查询

代码语言:javascript
复制
using namespace std;

Attributes a;
// Works even w/o special care.
a.SetAttr( "key1", string("foo") );

// Without the SetAttr() overload for strings, user would have to remind 
// to cast back to char const* when calling MyClass::GetAttr().
a.SetAttr( "key2", "bar" );

// Without the SetAttr() overload for strings, a later call to GetAttr()
// would cause a crash because we are passing pointers to temporary objects.
{
    // test arrays
    char temp1[] = { 'b', 'a', 'z', 0 };
    a.SetAttr( "key3", temp1 );
    char const temp2[] = { 'b', 'i', 'm', 0 };
    a.SetAttr( "key4", temp2 );

    // test pointers
    a.SetAttr( "key5", &temp1[0] );
    a.SetAttr( "key6", &temp2[0] );
}

try
{
    // When getting a string attribute we no longer have to care about how it was
    // passed to SetAttr(), we can simply cast to std::string in all cases.
    cout << "'" << a.GetAttr<string>( "key1" ) << "'" << endl;
    cout << "'" << a.GetAttr<string>( "key2" ) << "'" << endl;
    cout << "'" << a.GetAttr<string>( "key3" ) << "'" << endl;
    cout << "'" << a.GetAttr<string>( "key4" ) << "'" << endl;
    cout << "'" << a.GetAttr<string>( "key5" ) << "'" << endl;
    cout << "'" << a.GetAttr<string>( "key6" ) << "'" << endl;
}
// boost::type_erasure::bad_any_cast or std::out_of_range
catch( std::exception& e )
{
    cout << "Error: " << e.what() << endl;
}

Live Demo.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42837888

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档