将 std::vector 重命名为另一个类以进行重载



看看这段代码。

#include <vector>
template<class ...Args>
using other_vector = std::vector<Args...>;
template<class T>
void f(std::vector<T>& ) {}
template<class T>
void f(other_vector<T>& ) {}
int main()
{
    other_vector<int> b;
    f(b);
    return 0;
}

它不编译,因为正在重新声明f。我完全理解这个错误。但是,我需要第二个类,它的行为类似于 std::vector<T> ,但将被视为不同的类型,以便重载(如上例所示)是合法的。

我能做什么?

  • 让新类将std::vector<T>作为基类。这可能有效,但不应从 std 容器继承。
  • 让新类具有 std::vector 类型的成员,然后重新声明所有函数以重定向到成员的函数。听起来工作量很大。

还有更好的选择吗?允许C++11或C++14。

你可能会试图弄乱分配器:

template<class T>
struct allocator_wrapper : T { using T::T; };
template<class T, class A = std::allocator<T>>
using other_vector = std::vector<T, allocator_wrapper<A>>;

现场示例

如果您需要多个副本,可以将其制作为模板,并为"克隆编号"获取int模板

参数

您可以按如下方式包装您的类型:

// N allow to have several 'version' of the same type T
template <typename T, int N = 0>
class WrapperType
{
public:
    WrapperType() = default;
    WrapperType(const WrapperType&) = default;
    WrapperType(WrapperType&&) = default;
    template <typename ... Ts>
    explicit WrapperType(Ts&& ... ts) : t(std::forward<Ts>(ts)...) {}
    // implicit conversion
    // you may prefer make them explicit or use name get().
    operator const T& () const { return t; }
    operator T& () { return t; }
private:
    T t;
};

所以对于您的情况:

template<class T>
using other_vector = WrapperType<std::vector<T>>;

最新更新