禁止使用`static_assert`函数 [英] Forbids functions with `static_assert`

查看:234
本文介绍了禁止使用`static_assert`函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想防止某些函数被调用.让我们忽略通过函数指针或其他函数调用函数的情况,仅关注直接函数调用的情况.我可以用= delete做到这一点.但是,发出的诊断信息并不充分.我考虑过使用static_assert,您可以使用它提供自定义诊断消息.我在函数体内放置了static_assert(false, ...)语句,希望它在调用函数时触发.但是,事实证明即使未调用该函数,static_assert也将失败.有什么建议吗?

I want to prevent certain functions from being called. Let's ignore the case of calling the function via a function pointer or something, and just concentrate on the case of direct function call. I can do this with = delete. However, the diagnostic issued is not quite informative. I considered using static_assert, with which you can supply a custom diagnostic message. I placed a static_assert(false, ...) statement within the function body, hoping that it fires when the function is called. However, it turns out that the static_assert fails even if the function is not called. Any suggestions?

附加说明::无条件禁止该功能.因此,std::enable_if不适用于此处.使用此函数的动机是,我想防止某些使用,否则将使用重载分辨率很好地进行编译.因此,我不能只是删除该功能. deprecated不是我想要的.我想要编译错误,而不是警告.

Additional Note: The function is forbidden unconditionally. So, std::enable_if does not apply here. The motivation for such a function is that I want to prevent certain use, which would otherwise compile fine with overload resolution. So I can't just remove the function. deprecated is not what I want. I want a compilation error, not a warning.

推荐答案

我与其他人一样,您根本不应该使用static_assert并将功能标记为不推荐使用.

I agree with others that you shouldn't use static_assert for this at all and mark the function as deprecated instead.

static_assert离子在编译时触发.对于普通函数,这是它被解析的时间,而不是它被调用的时间.但是,对于template,它是实例化的时间.因此,您可以像这样将函数设置为template.

static_assertions fire at the time they are compiled. For an ordinary function, this is the time it is parsed, not the time it is called. For a template, however, it is the time of instantiation. So you can make your function a template like this.

template <typename...>
struct always_false { static constexpr bool value = false; };

template <typename... Ts>
void
never_call_me(Ts&&...)
{
  static_assert(always_false<Ts...>::value,
                "You should have never called this function!");
}

如果typename...不适合您(因为该函数已重载),请尝试将其范围缩小至仅与您要出错的内容相匹配.

If typename... is not right for you (because the function is overloaded), try narrowing it down to only match what you want to make an error.

此处使用的技巧是always_false<Ts...>::value取决于类型参数Ts...,因此在实例化template之前无法对其进行求值. (即使我们可以清楚地看到它始终是false.)

The trick used here is that always_false<Ts...>::value depends on the type parameters Ts... so it cannot be evaluated until the template is instantiated. (Even though we can clearly see that it will always be false.)

这篇关于禁止使用`static_assert`函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆