C ++:从盒装元素的向量构造一个Box类型的向量

时间:2017-05-10 17:59:54

标签: c++ c++11 templates visual-c++ boxing

以下是我的类型系统的简化摘录:

#include <string>
#include <vector>

template<typename T>
class Box {
public:
    Box(const T& value) : _value(value) {};
    T _value;
};

template <class T>
class Vector : protected std::vector<T> {
public:
    Vector() {}
    Vector(const std::vector<T>& values) { /* ...*/ }
    using std::vector<T>::push_back;
};

typedef Box<int> Int;
typedef Box<std::string> String;

int main(int argc, char* argv[]) {
    Vector<Int> v1;
    v1.push_back(Int(0));

    std::vector<String> strings2 = { String("a"), String("b") };
    Vector<String> v2(strings2);

    std::vector<std::string> strings3 = { "a", "b" };    
    // The following does not compile, since strings3 elements
    // are of the sub type
    Vector<String> v3(strings3);
}

如何定义允许最后一行编译的构造函数?

当然,对于这个小代码示例,VectorBox可能有更好的设计,但此处的类型过于简化。

1 个答案:

答案 0 :(得分:1)

您可以添加模板构造函数:

template <typename U,
          std::enable_if_t<std::is_constructible<T, U>::value>* = nullptr> 
Vector(const std::vector<U>& values);