我正在发布我自己问题的答案,希望澄清boost::type_erasure::any 的预期用途,而不会使原始问题过于冗长。
这个答案显示了一种可能的解决方法,将boost::type_erasure::any 隐藏在另一个类的接口后面,并为所有可转换为std::string 的类型提供setter 方法的重载。此重载负责将 char 指针和 char 数组转换为 std::string。
我认为一个额外的重载并没有那么糟糕,但理想情况下我想避免那个样板文件并使any 类型知道如何转换 C 字符串。这让我们回到了我的original question。
#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;
}
Live Demo.