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

时间:2014-01-07 13:59:32

标签: c++ c++11 stdvector

看看这段代码。

#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。

3 个答案:

答案 0 :(得分:17)

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

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>>;

Live example

答案 1 :(得分:0)

如果您需要多个副本,可以将其设为模板,并将int模板arg用于“克隆号”

答案 2 :(得分:0)

您可以将您的类型换行如下:

// 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>>;