有些晚了,但是可能有兴趣的人也可以使用
std::tuple
和类似于
std::for_each
的模板来迭代一个元组。
这是基于 ingomueller.net 在这个主题中的回答。
我最近遇到一种情况,需要创建一个属性映射(从 XML 文件读取配置值,主要是基本类型,并将它们插入到一个值类型为
any
的
std::unordered_map
中。出于调试目的,我希望能够打印整个地图及其键和值以及值的类型。
在那个项目中,我根本不使用 Boost,我使用了自己的
any
实现,但它非常类似于 boost::any。
插入运算符基本上看起来像这样:
template <typename TChar>
inline std::basic_ostream<TChar>&
operator<< (std::basic_ostream<TChar>& os, const sl::common::any& v)
{
std::tuple<
float, double, bool,
int8_t, uint8_t,
int16_t, uint16_t,
int32_t, uint32_t,
int64_t, uint64_t,
std::wstring, const wchar_t*,
StreamInserter::UnsupportedType> t;
StreamInserter si(os, v);
for_each(t, si);
return os;
}
for_each模板看起来像这样(C++14):
template <typename Tuple, typename F, std::size_t ...Indices>
constexpr void for_each_impl(Tuple&& tuple, F&& f, std::index_sequence<Indices...>) {
using swallow = int[];
(void)swallow{1,
(f(std::get<Indices>(std::forward<Tuple>(tuple))), void(), int{})...
};
}
template <typename Tuple, typename F>
constexpr void for_each(Tuple&& tuple, F&& f) {
constexpr std::size_t N = std::tuple_size<std::remove_reference_t<Tuple>>::value;
for_each_impl(std::forward<Tuple>(tuple), std::forward<F>(f),
std::make_index_sequence<N>{});
}
使用StreamInserter
类或与Ingos回答中显示的类似的东西即可。
希望这可以帮助到您。
boost::variant
吗?那会更简单 - 像any
这样的东西只是一开始看起来简单。 - Georg Fritzschemap<string,variant>
? - Frankboost::any
的。 - Frank