这个聚会有点晚了,但任何可能感兴趣的人也可以使用std::tuple
和一个类似std::for_each
模板的迭代元组的模板。
这是基于 ingomueller.net 在此线程中的答案。
我最近有一个案例,我创建了一个属性映射(从 XML 文件中读取配置值,主要是基本类型,并将它们插入到 中std::unordered_map
,其中值类型为 type any
。出于调试目的,我希望能够打印整个映射及其键和值以及值的类型。
在那个项目中,我根本没有使用Boost,我使用了自己的any
实现,但它与 boost::any 非常相似。
插入操作符基本上是这样的:
template <typename TChar>
inline std::basic_ostream<TChar>&
operator<< (std::basic_ostream<TChar>& os, const sl::common::any& v)
{
// Types that we support with sl::common::any.
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;
// Prepare ostream for printing a value of type any
StreamInserter si(os, v);
// Iterate over all types in tuple t. If the last type(UnsupportedType) is
// reached, given v is unsupported.
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 答案中显示的类或类似的东西。
希望这可以帮助。