如何解决条件模板类型数学
我有一个C ++函数,该函数接受uint8_t
数组来执行各种功能,这些函数需要uint16_t
并发出较小的uint8_t
数组。
对于uint16_t
输入,我可能需要一个uint32_t
数组,等等。
是否可以使用模板建立这种关系?类似于(用伪代码):
template <typename T,typename U = sizeof(T) * 2>
不幸的是,我实际上是在cython和c++的混合下工作,因此无法避免很多复制粘贴,但是我想知道在某些情况下这是否是一个选择。
解决方法
在c++17中,您可以提供一个帮助程序模板函数,您可以decltype
来查找要返回的数组的返回类型。
#include <cstdint>
#include <type_traits> // std::is_same_v
template <typename T>
auto ret_type_helper()
{
if constexpr (std::is_same_v <T,std::uint8_t>) return std::uint16_t{};
else if constexpr (std::is_same_v <T,std::uint16_t>) return std::uint32_t{};
else if constexpr (std::is_same_v <T,std::uint32_t>) return std::uint64_t{};
// else if constexpr... for another type.....
}
template <typename T>
auto func(const std::array<T /*,size */>& arr)
{
// use for getting the array's type,which you want to return from the function
using ReType = decltype(ret_type_helper<T>());
std::array<ReType /*,size */> result;
// ... code
return result;
}
,
您不能自动执行此操作,但是可以通过一些手动操作来实现:
template<typename> struct double_size_type;
template<> struct double_size_type<std::uint8_t> {
using type = std::uint16_t;
};
template<> struct double_size_type<std::uint16_t> {
using type = std::uint32_t;
};
template<> struct double_size_type<std::uint32_t> {
using type = std::uint64_t;
};
template<typename T,typename U = typename double_size_type<T>::type> {
// ...
};
对于每种受支持的类型T
,您需要提供专门的double_size_type<T>
。
我们可以将int的大小设为模板参数,因此Int<32>
表示32位整数。然后,您可以执行Int<sizeof(other_int) * 8 * 2>
,这意味着int的大小是other_int
的两倍:
#include <cstdint>
#include <type_traits>
// signed
template <std::size_t size>
using Int = std::conditional_t<size==8,std::int8_t,std::conditional_t<size==16,std::int16_t,std::conditional_t<size==32,std::int32_t,std::conditional_t<size==64,std::int64_t,void>>>>;
// unsigned
template <std::size_t size>
using UInt = std::conditional_t<size==8,std::uint8_t,std::uint16_t,std::uint32_t,std::uint64_t,void>>>>;
int main() {
// twice size of a regular int
Int<sizeof(int) * 8 * 2> i2 = 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。