問題描述
是否可以編寫一個值對所有常見 STL 結(jié)構(gòu)(例如,vector
、set
、map
、map
、...)?
首先,我想編寫一個類型特征,它對 vector
為真,否則為假.我試過這個,但它不能編譯:
template結(jié)構(gòu) is_vector {static bool const value = false;};模板<T類,U類>struct is_vector>>::類型>{static bool const value = true;};
錯誤信息是模板參數(shù)未用于部分特化:U
.
看,另一個基于 SFINAE 的用于檢測類 STL 容器的解決方案:
template結(jié)構(gòu) is_container : std::false_type {};模板結(jié)構(gòu) is_container_helper {};模板struct is_container<,std::conditional_t<錯誤的,is_container_helper<類型名稱 T::value_type,類型名稱 T::size_type,類型名稱 T::allocator_type,類型名 T::iterator,類型名 T::const_iterator,decltype(std::declval().size()),decltype(std::declval().begin()),decltype(std::declval().end()),decltype(std::declval().cbegin()),decltype(std::declval().cend())>,空白>>:公共 std::true_type {};
當(dāng)然,您可以更改要檢查的方法和類型.
如果您只想檢測 STL 容器(這意味著 std::vector
、std::list
等),您應(yīng)該執(zhí)行類似 這個.
更新.正如@Deduplicator 所指出的,容器可能不滿足 AllocatorAwareContainer 要求(例如:std::array
).這就是為什么不需要檢查 T::allocator_type
的原因.但是您可以以類似的方式檢查任何/所有Container要求.>
Is it possible to write a type trait whose value is true for all common STL structures (e.g., vector
, set
, map
, ...)?
To get started, I'd like to write a type trait that is true for a vector
and false otherwise. I tried this, but it doesn't compile:
template<class T, typename Enable = void>
struct is_vector {
static bool const value = false;
};
template<class T, class U>
struct is_vector<T, typename boost::enable_if<boost::is_same<T, std::vector<U> > >::type> {
static bool const value = true;
};
The error message is template parameters not used in partial specialization: U
.
Look, another SFINAE-based solution for detecting STL-like containers:
template<typename T, typename _ = void>
struct is_container : std::false_type {};
template<typename... Ts>
struct is_container_helper {};
template<typename T>
struct is_container<
T,
std::conditional_t<
false,
is_container_helper<
typename T::value_type,
typename T::size_type,
typename T::allocator_type,
typename T::iterator,
typename T::const_iterator,
decltype(std::declval<T>().size()),
decltype(std::declval<T>().begin()),
decltype(std::declval<T>().end()),
decltype(std::declval<T>().cbegin()),
decltype(std::declval<T>().cend())
>,
void
>
> : public std::true_type {};
Of course, you might change methods and types to be checked.
If you want to detect only STL containers (it means std::vector
, std::list
, etc) you should do something like this.
UPDATE. As @Deduplicator noted, container might not meet AllocatorAwareContainer requirements (e.g.: std::array<T, N>
). That is why check on T::allocator_type
is not neccessary. But you may check any/all Container requirements in a similar way.
這篇關(guān)于如何編寫類型特征“is_container"或“is_vector"?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!