![](/img/trans.png)
[英]How to cast, in C++, a byte vector (std::vector<uint8_t>) into different uint32_t, uint16_t and uint8_t variables
[英]Prevent duplicated code on different data types (uint16_t/ uint32_t)
我正在尋找使用函數的可能性,我將指針傳遞給uint16_t或uint32_t值。
目前我使用兩個重載函數
std::vector<float> calcMap(uint16_t* map)
std::vector<float> calcMap(uint32_t* map)
由於它們返回浮點值,因此對於16位和32位值的計算是相同的。 唯一的區別是通過指向的數組所需的數據類型。 我不希望兩次函數的全部內容,是否有可能使其獨立?
如果您只想接受uint16_t
和uint32_t
,那么以下幾行應該有效:
template <class T,
class = typename std::enable_if<
std::is_same<typename std::decay<T>::type, uint16_t>::value ||
std::is_same<typename std::decay<T>::type, uint32_t>::value>::type>
std::vector<float> calcMap(T * map) {
// Code
}
你必須#include <type_traits>
並啟用至少C ++ 11以使上述工作正常。
順便說一下,如果你的代碼只讀取數據,那么將T *
改為T const *
可能是個好主意。 或者地獄, T const * const
而你在它。
您可能也對std::is_integral
,以防您只想允許超過上面使用的2種類型。
主要是為了完整性:
如果你不希望暴露的,而不管出於什么原因不想轉發到私模板函數的實現。 經常忽略顯式模板實例化聲明的選項。 這很容易:
聲明一個模板,並在標頭中顯式聲明它的實例化:
template<typename T> std::vector<float> calcMap(T*); extern template std::vector<float> calcMap<>(uint16_t*); extern template std::vector<float> calcMap<>(uint32_t*);
在您自己的原始翻譯單元中,定義一個模板,並添加兩個顯式實例:
template<typename T> std::vector<float> calcMap(T*) { // Now we implement } template std::vector<float> calcMap<>(uint16_t*); // Now this will link template std::vector<float> calcMap<>(uint32_t*); // As will this
與drescherjm的優秀建議有什么不同? 它會產生更少的符號。 如果您的編譯器在鏈接時內聯方面不太好,則不需要它跳過轉發函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.