I am debugging a metafunction that iterates over a variadic template parameter and checks pairs (Type, Tag) to see if each Type is tagged with the corresponding Tag:
template<typename Type, typename Tag, typename ... Rest>
constexpr bool taggedTypes()
{
constexpr std::size_t restN = sizeof ...(Rest);
static_assert(restN % 2 == 0, "Odd number of (Type, Tag) pairs.");
constexpr bool pairDoesntMatch = ! taggedType<Type, Tag>();
if constexpr (pairDoesntMatch)
return false;
// Single pair, empty Rest, pair matches.
if (restN == 0)
return true;
// More than two pairs, test further.
if (restN > 2)
taggedTypes<Rest...>();
return true;
}
Something is wrong with my code, and I want to debug it.
If I use static_assert to output restN or any other constexpr variable, my program will break at compile time at the point of assertion with an output I prescribe. Also, it is not clear to me yet how to write down anything apart from a string literal with static_assert().
How can I make the metaprogram iterate over the variadic template parameter and output stuff that I need for debugging?
The complete example:
#include <cassert>
#include <type_traits>
#include <cstddef>
struct fruit_tag {};
struct veggie_tag {};
template<typename T>
struct tag;
template<typename T, typename Tag>
constexpr
bool
taggedType()
{
constexpr bool sameTypes
= std::is_same<typename tag<T>::type, Tag>();
static_assert(sameTypes);
return sameTypes;
}
template<typename Type, typename Tag, typename ... Rest>
constexpr bool taggedTypes()
{
constexpr std::size_t restN = sizeof ...(Rest);
static_assert(restN % 2 == 0, "Odd number of (Type, Tag) pairs.");
constexpr bool pairDoesntMatch = ! taggedType<Type, Tag>();
if constexpr (pairDoesntMatch)
return false;
// Single pair, empty Rest, pair matches.
if (restN == 0)
return true;
// Many pairs, test further.
if (restN > 2)
taggedTypes<Rest...>();
return true;
}
class Orange {};
template<>
struct tag<Orange>
{
using type = fruit_tag;
};
class Apple {};
template<>
struct tag<Apple>
{
using type = fruit_tag;
};
class Turnip{};
template<>
struct tag<Turnip>
{
using type = veggie_tag;
};
int main()
{
static_assert(taggedTypes<Turnip, veggie_tag, Orange, fruit_tag>());
};