[英]Trigger compile time error when given overload of the constexpr function is called
I am writing custom variadic template that performs lookup in compile-time map.我正在编写在编译时映射中执行查找的自定义可变参数模板。
The problem is, I want to trigger compile-time error each time the value is not found in that map - preferably with descriptive error message.问题是,每次在该映射中找不到该值时,我都想触发编译时错误 - 最好带有描述性错误消息。
example code:示例代码:
template<key_t k, class pair, class... pairs>
static constexpr value_t get_local(std::tuple<pair, pairs...>)
{
return (pair::key == k) ? pair::value : get_local<k>(std::tuple<pairs...>{});
}
template<key_t k> static constexpr value_t get_local(std::tuple<>)
{
// Trigger error!
}
I can leave get_local
undefined in the second part of code, and it actually triggers linker error, but that is not falling into category of "descriptive error message".我可以在代码的第二部分中保留get_local
未定义,它实际上会触发链接器错误,但这不属于“描述性错误消息”的类别。
Static asserts, I believe, would be of no use here.我相信静态断言在这里没有用处。
I am using C++ 17我正在使用 C++ 17
And immediate drop in solution is to delete
the overload:立即删除解决方案是delete
重载:
template<key_t k> static constexpr value_t get_local(std::tuple<>) = delete;
This will provide the somewhat descriptive message that we try to use a base case that doesn't exist.这将提供一些描述性信息,即我们尝试使用不存在的基本情况。
Alternatively, with a static assertions in place:或者,使用静态断言:
template<key_t k> struct always_false { static constexpr bool value = false; };
template<key_t k> static constexpr value_t get_local(std::tuple<>)
{
static_assert(always_false<k>::value, "Hit bad case!");
return std::declval<value_t>();
}
The always_false
utility is needed to make the assertion condition dependent, so the template is not ill-formed;需要使用always_false
实用程序来使断言条件依赖,因此模板不会格式错误; no diagnostic required, as static_assert(false, ...)
would make it.不需要诊断,因为static_assert(false, ...)
可以做到。
Mind you, that you instantiate this overload yourself in your own conditional operator:请注意,您自己在自己的条件运算符中实例化了这个重载:
(pair::key == k) ? pair::value : get_local<k>(std::tuple<pairs...>{});
When you hit the case of a tuple with a single element.当您遇到具有单个元素的元组时。 Both "branches" of the conditional expression must be valid.条件表达式的两个“分支”都必须有效。 Best handle it conditionally with an if constepxr
:最好使用if constepxr
有条件地处理它:
if constexpr (pair::key == k) return pair::value;
else return get_local<k>(std::tuple<pairs...>{});
Since you did indicate pair::key == k
can be evaluated in a constant expression.由于您确实表示可以在常量表达式中计算pair::key == k
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.