【问题标题】:Convert Template Parameter in Typedef在 Typedef 中转换模板参数
【发布时间】:2016-10-13 13:32:18
【问题描述】:

我正在编写一个类,该类需要它被实例化的模板类型在位移操作下表现得像无符号类型。之所以如此,是因为移位操作下的负数与移位操作下的正数表现不同。因此,我的想法是简单地将我作为模板参数获得的任何类型转换为 typedef 中它的无符号版本,并且在内部仅使用 typedefed 版本。如果模板参数类型不支持这一点,那么......它根本不支持,并且会出现编译时错误。我尝试的看起来像这样:

template <class X>
class C
{
    using Y = unsigned X;
};

不正确:error: type-id cannot have a name

这有可能吗?如果可以,怎么办?

【问题讨论】:

    标签: c++ templates type-conversion typedef


    【解决方案1】:

    你正在寻找std::make_unsigned:

    template <class X>
    class C
    {
        using Y = std::make_unsigned_t<X>;
    };
    

    【讨论】:

    • @NathanOliver:你的意思是typename std::make_unsigned&lt;X&gt;::typewandbox - std::make_unsigned_t 是一个 C++14 别名,别名中不需要尾随 ::type
    • 注意:您错过了无效类型的编译时错误,您目前只有 UB。 static_assert(std::is_signed&lt;T&gt;::value || std::is_unsigned&lt;T&gt;::value, "Expected signed/unsigned type");
    • 对不起。最后错过了_t
    猜你喜欢
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多