在编译时根据参数大小选择函数

Choosing function at compile time based on argument size

本文关键字:选择 函数 参数 编译      更新时间:2023-10-16

有没有一种方法可以生成代码(在编译时),看起来有点像:

T Func(T t){
    if (sizeof(t) == 2){
        return X(t);
    }
    else if( sizeof(t) == 4){
        return Y(t);
    }
}

(其中T是int32或int16)

所以在运行时我可以调用:

Func(_myInt)

代码将编译为X(_myInt)Y(_myInt)

是。

X Func(int32_t t) {
    return X(t);
}
Y Func(int16_t t) {
    return Y(t);
}

通过标签调度:

template <typename T>
auto Func_impl(T t, std::integral_constant<std::size_t, 2>){
   return X(t);
}
template <typename T>
auto Func_impl(T t, std::integral_constant<std::size_t, 4>){
   return Y(t);
}
template <typename T>
auto Func(T t){
   return Func_impl(T, std::integral_constant<std::size_t, sizeof(T)>{});
}

为了完整性,如果您只想按绝对大小进行调度,还有enable_if:

#include <utility>
#include <cstdint>
template <typename T, std::enable_if_t<sizeof(T) == 2>* = nullptr>
auto Func(T t){
}
template <typename T, std::enable_if_t<sizeof(T) == 4>* = nullptr>
auto Func(T t){
}
int main()
{
  Func(std::uint16_t(10));
  Func(std::uint32_t(10));
}