我有一個 100% 作業代碼,它使用 C 樣式#defines,但應該轉換為 c 樣式(使用 =),因為這是其余代碼的樣式。
我不精通 C 并且努力轉換 ::value 表示法。
我的代碼檢查容器(如vector/set/map)及其元素是否使用相同的分配器。
template <typename Cont, typename elem>
using allocIsRecursive = typename std::uses_allocator<elem, typename Cont::allocator_type>;
template <typename Cont>
using allocIsTrivial = typename std::uses_allocator<Cont, std::allocator<char>>;
// Here are 2 defines which I wrote and am struggling to convert....
#define allocShouldPropagate(Cont, elem) \
(allocIsRecursive<Cont, typename Cont::elem>::value && !allocIsTrivial<Cont>::value)
#define allocShouldPropagateMap(Map) (allocShouldPropagate(Map, key_type) || allocShouldPropagate(Map, mapped_type))
*~~~~~~~~~~~~~~~~~~~~~
更多背景關系:通過默認的空建構式將新元素插入容器時使用該代碼。如果應該傳播容器,則使用分配器感知建構式。
向量示例:
template <typename C>
std::enable_if_t<allocShouldPropagate(C, value_type), typename C::value_type>
defaultVectorElement(C& c) {
return typename C::value_type{c.get_allocator()};
}
template <typename C>
std::enable_if_t<!allocShouldPropagate(C, value_type), typename C::value_type>
defaultVectorElement(C& c) {
return typename C::value_type{};
}
注意:std::scoped_allocator_adaptor<> 做一些類似于簡單容器的事情,但它不適用于復雜的容器,比如地圖、哈希表, 它有一個可測量的 CPU 損失。
uj5u.com熱心網友回復:
這是你想要的?
template <typename Cont, typename elem>
constexpr bool allocIsRecursive_v = std::uses_allocator<elem, typename Cont::allocator_type>::value;
template <typename Cont>
constexpr bool allocIsTrivial_v = std::uses_allocator<Cont, std::allocator<char>>::value;
template <typename Cont, typename elem>
constexpr bool allocShouldPropagate_v = allocIsRecursive_v<Cont, typename Cont::elem> && !allocIsTrivial_v<Cont>;
template <typename Map>
constexpr bool allocShouldPropagateMap_v = allocShouldPropagate_v<Map, typename Map::key_type> || allocShouldPropagate_v<Map, typename Map::value_type>;
然后在您的用例中,您將更allocShouldPropagate(C, value_type)改為allocShouldPropagate_v<C, typename C::value_type>.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/508185.html
上一篇:模板化類中的成員變數
