也許我不是第一個發現std::exception_ptr
可以用來實現any
類型(性能考慮被擱置)的第一人,因爲它可能是C++中唯一可以使用的類型抱什麼。但是,谷歌搜索沒有在這個方向上帶來任何結果。std :: any std :: exception_ptr
有誰知道以下方法是否在任何有用的地方使用過?
#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;
}
我編輯了代碼。我認爲它不再分割。 – JohnB
g ++ 4.8.4不會產生一千萬個'Any'並將它們存儲在'vector'中。然而,它非常緩慢。 (30秒設置並獲得1000萬個值)。 – JohnB
實際上,我一直認爲更好的技巧(因爲它自C++ 98開始可用)將使用'std :: locale',存儲任何你想要的作爲一個方面。 –