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


是否可以

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

默认情况下,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;
}

现场演示。

不,any存储任何内容。 const char*什么都不是。

请注意,"hello"s是类型 std::string 的文本。

我发布了我自己问题的答案,希望澄清boost::type_erasure::any的预期用途,而不会使原始问题过于冗长。

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

我认为一个额外的重载并不是那么糟糕,但理想情况下,我想避免使用样板文件并使any类型知道如何转换 C 字符串。这让我们回到我最初的问题。

#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::SetAttr()并通过 Attributes::GetAttr<std::string>() 进行一般查询:

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;
}

现场演示。

相关内容

最新更新