Thursday 26th May 2016: 8.20am. Link shared: http://melpon.org/wandbox/permlink/4rJCUypvBbGGFTqx
I'm not a natural C++ metaprogrammer, so it took me two mornings before work to come up with this of which I am quite proud:
```
#include <stdio.h>
#include <string>
template <class... Args> struct Foo {};
template <class T, class... Args> struct Foo<T, Args...> {
T v;
Foo<Args...> rest;
};
template <class T> struct Foo<T> { T v; };
namespace detail {
template <size_t N, class T, class... Args> struct getFoo {
constexpr auto operator()(const Foo<T, Args...> &f) const {
return getFoo<N - 1, Args...>()(f.rest);
}
};
template <class T, class... Args> struct getFoo<0, T, Args...> {
constexpr const T &operator()(const Foo<T, Args...> &f) const { return f.v; }
};
}
template <size_t idx, class... Args> constexpr auto get(const Foo<Args...> &f) {
return detail::getFoo<idx, Args...>()(f);
}
int main(void) {
// Constexpr test
constexpr Foo<int, double, const char *> fc[] = {{1, 1.0, "hi1"},
{2, 2.0, "hi2"}};
// STL container test
std::initializer_list<Foo<int, double, const char *, std::string>> fn = {
{1, 1.0, "hi1", std::string("foo1")},
{2, 2.0, "hi2", std::string("foo2")}};
printf("%d, %f, %s\n", get<0>(fc[0]), get<1>(fc[0]), get<2>(fc[0]));
auto s(fn.begin());
++s;
printf("%d, %f, %s\n", get<0>(*s), get<1>(*s), get<2>(*s));
return 0;
}
```
It's a tuple right? Actually no, rather it's an aggregate initialisable tuple of heterogeneous types as std::tuple can only be constructed using braced initialisers i.e. the {1, 1.0, "hi1", std::string("foo1"), but not initialised. Confused? Yeah, that's C++ for you, but basically you can't initialise arrays or lists of std::tuple via C array type lists because std::tuple isn't built to allow it. My tuple above you can, and that's exactly what I was looking for as my current before work work item requires the ability to concisely specify lists of things where those things are freeform.
Problem solved, yay! And works in VS2015 Update 2, GCC and clang as you can see at http://melpon.org/wandbox/permlink/4rJCUypvBbGGFTqx.
#c++ #boostcpp #boostafio #boostoutcome #boostkerneltest #boostlite