看看这段代码。
#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容器继承。还有更好的选择吗?允许使用C ++ 11或C ++ 14。
答案 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>>;
答案 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>>;