有没有办法在编译器警告消息中获取模板类型的类型名称?

时间:2018-06-15 13:54:40

标签: templates c++17 compiler-warnings preprocessor static-assert

当我们使用T,U类型模板自动转换为静态但可能是一个有问题的用例时,我很乐意警告自己或其他人,以便程序员可以验证该模板是否合适(或者如果他们在某处犯了错误在他们的元逻辑中。)

但是我无法辨别出如何生成这样的编译时警告,这些警告命名类型或以任何方式引用调用者的代码?

如果是故障情况 - 那么我可以发出static_assert或类似的命令以强制编译器失败,然后用户将在输出诊断中看到最初触发故障情况的内容。

但是一个有问题的用例呢?不一定是错误......只是一个警告?

这是我的意思的一个例子:

template <typename T, typename U>
bool within(T value, U minimum, U maximum)
{
    // WARNING: we force U to be a T silently
//#pragma message("Forcing " typeid(U).name() " to a " typeid(T).name())
#pragma message("Possible casting danger is happening in this template - check your types!")
    return static_cast<T>(minimum) <= value && value <= static_cast<T>(maximum);
}

在这里,我无法弄清楚如何命名T和U,也不知道如何回到调用者的代码......

我想我想要一个

static_warning(condition, "optional text which somehow also produces the actual typename of T and U");

想法?

1 个答案:

答案 0 :(得分:0)

好的 - 所以我很乐意听到社区关于生成编译时类型相关警告消息的方法......

但与此同时,我意识到C ++ 17实际上拥有我需要的解决方案,以及类似(T,U)静脉的解决方案:

// this will only compile if there is a common type for T and U! Neat! :D
template <typename T, typename U, typename Z = std::common_type_t<T,U>>
bool within(T value, U minimum, U maximum)
{
    return static_cast<Z>(minimum) <= value && value <= static_cast<Z>(maximum);
}