条件模板类型数学

问题描述

我有一个C ++函数,该函数接受uint8_t数组来执行各种功能,这些函数需要uint16_t并发出较小的uint8_t数组。

对于uint16_t输入,我可能需要一个uint32_t数组,等等。

是否可以使用模板建立这种关系?类似于(用伪代码):

template <typename T,typename U = sizeof(T) * 2>

不幸的是,我实际上是在的混合下工作,因此无法避免很多复制粘贴,但是我想知道在某些情况下这是否是一个选择。

解决方法

中,您可以提供一个帮助程序模板函数,您可以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; 
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...