gpt4 book ai didi

c++ - 有什么方法可以获取容器模板类型以将其与另一个 value_type 重用吗?

转载 作者:行者123 更新时间:2023-11-30 05:05:45 26 4
gpt4 key购买 nike

我有一个在 typename ContainerType 上参数化的函数模板,它接受一个 const ContainerType& 参数。它将容器内的每个元素转换为其他类型,并(当前)返回转换后类型的 std::vector

有什么方法可以“借用”推导出的 ContainerType 的实际外部类模板?我目前有 this code returning the hardcoded vector :

template<typename ContainerType, typename OutputType = decltype(convert(std::declval<typename ContainerType::value_type>()))>
std::vector<OutputType> convert(const ContainerType& input)
{
std::vector<OutputType> result;
result.reserve(input.size());
std::transform(input.begin(), input.end(),
std::back_inserter(result),
static_cast<OutputType(*)(typename ContainerType::value_type)>(&convert));
return result;
}

我想推导出仅从其 value_type 剥离的类模板。请记住,容器通常有超过 1 个模板参数(数量因容器和实现而异),因此 ContainerType 的模板模板参数不是此处的解决方案。

最佳答案

这太骇人听闻了,并且不适用于 map 。我建议重新考虑您的界面。

template<bool isAlloc, class From, class Of, class With>
struct rebind_arg { using type = From; };

template<bool isAlloc, class From, class Of, class With>
using rebind_arg_t = typename rebind_arg<isAlloc, From, Of, With>::type;

// allocators need to be rebound with allocator_traits
template<class From, class Of, class With>
struct rebind_arg<true, From, Of, With> {
using type = typename std::allocator_traits<From>::template rebind_alloc<With>;
};

// Try to rebind non-allocator arguments
template<class T, class With>
struct rebind_arg<false, T, T, With> { using type = With; };

template<template<class...> class X, class T, class... Args, class With>
struct rebind_arg<false, X<Args...>, T, With> {
using type = X<rebind_arg_t<false, Args, T, With>...>;
};

// resolve an ambiguity
template<template<class...> class X, class... Args, class With>
struct rebind_arg<false, X<Args...>, X<Args...>, With> {
using type = With;
};

// Obtain the container's allocator type if it has one
template<class T, class=void>
struct get_allocator_type { struct none; using type = none; };

template<class T>
struct get_allocator_type<T, std::void_t<typename T::allocator_type>> {
using type = typename T::allocator_type;
};

// Check if a type is the allocator type of another type
template<class T, class C>
constexpr bool is_allocator_of = std::is_same_v<T, typename get_allocator_type<C>::type>;

template<class C, class With>
struct rebind_container;

template<template<class...> class X, class... Args, class With>
struct rebind_container<X<Args...>, With> {
using Source = X<Args...>;
using type = X<rebind_arg_t<is_allocator_of<Args, Source>, Args,
typename Source::value_type, With>...>;
static_assert(!std::is_same_v<Source, type>, "Rebinding unsuccessful");
};

template<class C, class With>
using rebind_container_t = typename rebind_container<C, With>::type;

关于c++ - 有什么方法可以获取容器模板类型以将其与另一个 value_type 重用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48241349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com