我試圖寫一個模板輸入驗證方法,如果輸入的是哪些測驗std::string,std::vector或std::array。但是對于后者,我遇到了一個問題,因為我必須為型別定義提供一個恒定的長度。
所以當我呼叫std::is_same<T, std::array<uint8_t, container.size()>>::value編譯器的時候會生氣(有道理 container.size() 不是靜態的)。有沒有辦法解決這個問題?
我事先不知道容器的大小,我永遠不會知道:(
template<typename T> bool valid_container_type(const T& container)
{
(void) container;
if constexpr (std::is_same<T, std::vector<uint8_t>>::value)
{
return true;
}
else if constexpr (std::is_same<T, std::vector<char>>::value)
{
return true;
}
else if constexpr (std::is_same<T, std::array<char, container.size()>>::value)
{
return true;
}
else if constexpr (std::is_same<T, std::array<uint8_t, container.size()>>::value)
{
return true;
}
else if constexpr (std::is_same<T, std::string>::value)
{
return true;
}
return false;
}
uj5u.com熱心網友回復:
問題是它container.size()不是常量運算式,不能用作非型別模板引數。
可以在編譯時添加一個type trait來獲取大小(或者std::tuple_size直接使用@康桓瑋評論)。例如
template <typename>
struct get_array_size;
template <typename T, size_t S>
struct get_array_size<std::array<T, S>> {
constexpr static size_t size = S;
};
然后將其用作:
if constexpr (std::is_same<T, std::array<uint8_t, get_array_size<T>::size>>::value)
請注意,您必須將if分支 for移動到std::stringbefore 之前std::array。否則,您也需要size在主模板中定義(并為其指定默認值)。
uj5u.com熱心網友回復:
您可以檢查 someT是否是這樣的std::ararywith 元素uint8_t:
#include <iostream>
#include <array>
#include <type_traits>
template <typename T>
struct is_uint8_t_array : std::false_type {};
template <size_t S>
struct is_uint8_t_array< std::array<uint8_t,S> > : std::true_type {};
int main() {
std::cout << is_uint8_t_array<std::array<uint8_t,32>>::value << "\n"; // 1
std::cout << is_uint8_t_array<std::array<int,42>>::value << "\n"; // 0
std::cout << is_uint8_t_array<int>::value << "\n"; // 0
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/326462.html
上一篇:未宣告的識別符號-模板C
下一篇:如何將我的模板從胡子轉換為車把?
