gpt4 book ai didi

c++ - 编译时排除部分函数模板

转载 作者:行者123 更新时间:2023-11-30 03:36:43 25 4
gpt4 key购买 nike

请考虑以下代码。它是一个函数模板,根据其位宽对 T 类型进行操作。实际代码更复杂,但这无关紧要:

template <typename T> T MyFunc(T t)
{
constexpr const uint8_t typeBitCount = sizeof(T)*8;

// more code here that works fine for all widths

if (typeBitCount >= 32)
{
if (...)
{
return t >> 16; // warning right shift count >= width of type
}

if (typeBitCount >= 64)
{
if (...)
{
return t >> 32; // warning right shift count >= width of type
}
}
}
}

我也将其用于 8 位类型。在那种情况下,我会收到警告(请参阅注释行)。不幸的是,即使使用 constexpr,C++ 也无法在编译期间评估 if 条件。我可能可以抑制警告,但这对我来说似乎很老套。我宁愿在编译时排除有问题的代码。

如何解决这个问题(可能不会将代码分解成碎片并且不会产生冗余)?

我正在使用 GCC 5.4.0。

最佳答案

我会计算有问题的转变,以便:

  • 当要执行移位时,它具有所需的值32,
  • 如果它不应该被执行,它有一些小值 0:

    ....
    constexpr uint8_t shift2 = (typeBitCount >= 64) ? 32 : 0;
    ....
    if (typeBitCount >= 64)
    {
    if (...)
    {
    return t >> shift2;
    }
    }
    ....

关于c++ - 编译时排除部分函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40561437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com