【发布时间】:2019-01-09 21:09:01
【问题描述】:
我正在调试一个元函数,它遍历可变参数模板参数并检查对(Type、Tag)以查看每个 Type 是否被相应的 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;
}
我的代码有问题,我想调试它。
如果我使用static_assert 输出restN 或任何其他constexpr 变量,我的程序将在编译时在断言点中断,并输出我规定的输出。此外,我还不清楚如何用static_assert() 写下除字符串文字之外的任何内容。
如何使元程序迭代可变参数模板参数并输出调试所需的内容?
完整的例子:
#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>());
};
【问题讨论】:
-
我没有仔细阅读这篇文章,所以这不是一个答案,但this page 讨论了 Erwin Unruh 在编译时使用素数生成错误消息的技术。该页面还讨论了该技术的 C++17 更新。
标签: c++ debugging c++17 variadic-templates template-meta-programming