在编译时根据参数大小选择函数
Choosing function at compile time based on argument size
有没有一种方法可以生成代码(在编译时),看起来有点像:
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));
}
相关文章:
- 如何基于循环迭代器选择函数
- 控件不会在选择函数旁边移动
- 函数模板 - 使用同一类型调用时,使用不同的参数类型选择函数
- 使用声明类型选择函数专业化
- 如何使“确认选择”函数从“主要”取消,如果它是假的
- 在编译时根据参数大小选择函数
- 在选择函数中检测超时的客户端
- 如何选择函数模板专用化
- 如何编写用于选择函数的样板代码
- "string_literal"解析为布尔值,但不解析为 std::string,当编译器选择函数的重载版本时
- 如何在编译时根据 constexpr 结果选择函数
- 使用模板选择函数的正确版本
- 在选择函数中等待fd的异常条件是什么?
- 矢量扩展的最佳选择函数
- 根据运行时数据选择函数重载
- 选择函数一直返回-1
- 在运行时选择函数参数
- 使用SFINAE根据函数是否存在特定的过载来选择函数
- 如何在c++中使用namespace::function选择函数的单个重载
- 根据模板参数选择函数名称