I've written a compile time search and find through template parameters, and it's working fine. I'm stumped about how to go about providing a default value for when there is no item found.
I've tried using sizeof...(args_t) to create a template specialization to terminate on. That isn't allowed. And so, I'm not sure how to go about doing this.
Here's what I've got right now:
template <typename... args_t> class c
{
template <size_t pos, typename _t, typename... a_t> struct at : at<pos - 1, a_t...> { };
template <typename _t, typename... a_t> struct at<0, _t, a_t...>
{
using t = _t;
};
};
What I need is something like:
template <typename... args_t> class c
{
template <> struct at<sizeof...(args_t)>
{
using t = default_value;
};
};
So, how do I go about creating a template specialization based on the number of variadic elements?
You may use the following to manage case where index is outside bound:
template <typename... args_t> class c
{
template <std::size_t pos, typename... Ts> struct at;
template <std::size_t pos, typename T, typename... Ts>
struct at<pos, T, Ts...> : at<pos - 1, Ts...>
{};
template <typename T, typename... Ts>
struct at<0, T, Ts...>
{
using type = T;
};
template <std::size_t N>
struct at<N>
{
using type = void; // default type
};
};
Or using std::tuple
and std::conditional
(with lazy evaluation):
template <typename... args_t> class c
{
public:
struct default_type { using type = void; };
template <std::size_t pos, typename... Ts>
struct at
{
using type =
typename std::conditional<
(pos < sizeof...(Ts)),
std::tuple_element<pos, std::tuple<Ts...>>, // don't use ::type here
default_type
>::type::type; // expand type 'twice'.
};
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments