我最近开始使用 Boost
C++ 库,我正在测试 any
可以容纳任何数据类型的类。实际上我正在尝试定义 operator<<
轻松打印 any
类型的任何变量的内容(当然,内容的类别也应该定义 operator<<
)。
我只从示例类型( int
、 double
...)开始,因为默认情况下会显示它们。到目前为止,我有这段代码:
#include <boost/any.hpp>
#include <iostream>
#include <string>
using namespace std;
using namespace boost;
ostream& operator<<(ostream& out, any& a){
if(a.type() == typeid(int))
out << any_cast<int>(a);
else if(a.type() == typeid(double))
out << any_cast<double>(a);
// else ...
// But what about other types/classes ?!
}
int main(){
any a = 5;
cout << a << endl;
}
所以这里的问题是我必须枚举所有可能的类型。有没有办法将变量转换为 particular type
拥有type_info
这个 particular type
?
最佳答案
Boost.Any any
与 boost::any
您不能像其他人已经在评论中指出的那样这样做。那是因为 boost::any
忘记关于它存储的值(value)类型的一切,并要求你知道那里有什么类型。虽然您无法枚举所有可能的类型。
解决办法是改成boost::any
这样它就忘记了有关它存储的值类型的所有信息,除了如何将其流出。 Mooing Duck 在评论中提供了一种解决方案。另一种方法是编写一个新版本的 boost::any
但扩展其内部结构以支持流操作。
boost spirit hold_any
Boost.Spirit 已经在 <boost/spirit/home/support/detail/hold_any.hpp>
中提供了类似的东西.
Boost.TypeErasure any
然而,更好的方法是使用 Boost.TypeErasure的 any
正如 Kerrek SB 在他的评论中提到的那样。
您的案例示例(使用 <<
)如下所示:
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/operators.hpp>
#include <iostream>
#include <string>
int main() {
typedef
boost::type_erasure::any<
boost::mpl::vector<
boost::type_erasure::destructible<>,
boost::type_erasure::ostreamable<>,
boost::type_erasure::relaxed
>
> my_any_type;
my_any_type my_any;
my_any = 5;
std::cout << my_any << std::endl;
my_any = 5.4;
std::cout << my_any << std::endl;
my_any = std::string("text");
std::cout << my_any << std::endl;
}
关于c++ - 将 boost::any 实例转换为其真实类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26268330/