根据数字模板参数有条件地编译转换运算符 [英] Conditionally compile a conversion operator based on numeric template parameter

查看:72
本文介绍了根据数字模板参数有条件地编译转换运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板< bool P> Foo 类,其中包含大量代码。我希望能够将 Foo< true> 转换为 Foo< false> ,即运算符Foo< false>()方法。但是编译器不喜欢Foo现有的这种方法,它只喜欢 Foo< true> 的方法,并警告如何不调用运算符用于隐式或显式转换(GCC 5.4.x)

I have a template <bool P> class Foo with lots of code in it. I want to be able to convert Foo<true>'s into Foo<false>'s, i.e. have an operator Foo<false>() method. But the compiler doesn't like such a method existing for Foo, it only likes it for Foo<true>, and gives a warning about how the "operator will not be called for implicit or explicit conversions" (GCC 5.4.x)

似乎我不能为此使用SFINAE: std :: enable_if 适用于类型;我尝试了一个值变量(真实情况下的值是 value 而不是 type 成员)没有

It doesn't seem like I can use SFINAE for this: std::enable_if works with types; and a value-variant I tried out (where the true case has a value rather than a type member) didn't help either.

如何才能仅针对 Foo< false> (除了

到目前为止,我最好的尝试是:尝试将 Foo< false> 不同并复制我的所有代码)?

My best attempt so far has been:

template <bool P> class Foo {
    // etc. etc.
    template <bool OtherValue>
    operator Foo<OtherValue>()
    {
        static_assert(OtherValue, "You should not be using this conversion!");
        // conversion code here
        return Foo<false>(args,go,here);
    }
}


推荐答案


如何才能仅针对 Foo< false> 编译此运算符(而不是专门针对 Foo< false> 不同并复制我所有的代码)?

How can I get this operator to only be compiled for Foo<false> (other than specializing Foo<false> different and duplicating all of my code)?



template <bool P> 
struct Foo 
{
    template <bool P2 = P, typename = std::enable_if_t<P2 == true>>
    operator Foo<false>()
    {
        return {};
    }
};

使用 P2 = P 会延迟对 enable_if_t 到实际使用转换运算符的时间(而不是类实例化)

Using P2 = P delays the evaluation of the enable_if_t to when the conversion operator is actually being used (instead of class instantiation).

如果我们尝试简单地写:

If we tried to simply write:

template <typename = std::enable_if_t<P == true>>
operator Foo<false>()
{
    return {};
}

std :: enable_if_t< P == true> 将在 Foo< P> 的实例化期间进行评估,因为在实例化成员函数时不会发生替换。实例化 Foo 时发生替换-因此SFINAE无法发生(因为尚未设置任何重载解决方案)

std::enable_if_t<P == true> would be evaluated during Foo<P>'s instantiation as there is no substitution occurring when the member functions are instantiated. The substitution is happening when Foo is instantiated - therefore SFINAE cannot take place (as there isn't any overload resolution set yet).

通过添加 bool P2 = P 默认参数,我们将替换延迟到转换运算符的实例化上。

By adding a bool P2 = P default parameter, we delay substitution to the instantiation of the conversion operator. This happens during overload resolution, so SFINAE can take place.

此答案比我能更好地解释:https://stackoverflow.com/a/13401982/598696

This answer explains it better than I can: https://stackoverflow.com/a/13401982/598696

这篇关于根据数字模板参数有条件地编译转换运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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