【发布时间】:2015-12-21 08:13:48
【问题描述】:
可能我不是第一个发现std::exception_ptr 可用于实现any 类型(性能考虑暂且不提)的人,因为它可能是C++ 中唯一可以容纳任何东西的类型。然而,谷歌搜索并没有在这个方向上带来任何结果。
有人知道以下方法是否已用于任何有用的地方吗?
#include <exception>
#include <iostream>
struct WrongTypeError : std::exception { };
class Any {
public:
template <class T>
void set (T t) {
try { throw t; }
catch (...) { m_contained = std::current_exception(); }
}
template <class T>
T const & get () {
try { std::rethrow_exception (m_contained); }
catch (T const & t) { return t; }
catch (...) { throw WrongTypeError {}; }
}
private:
std::exception_ptr m_contained = nullptr;
};
int main () {
auto a = Any {};
a.set (7);
std::cout << a.get<int> () << std::endl;
a.set (std::string {"Wonderful weather today"});
std::cout << a.get<std::string> () << std::endl;
return 0;
}
【问题讨论】:
-
我已经编辑了代码。我认为它不再切片了。
-
g++ 4.8.4 在生成一千万个
Anys 并将它们存储在vector中没有问题。然而,它非常缓慢。 (设置和获取这 1000 万个值需要 30 秒。) -
实际上,我一直认为更好的技巧(因为它从 C++98 开始可用)是使用
std::locale,将您想要的任何内容存储为方面。