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


以下是

我的类型系统的简化摘录:

#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设计,但这里的类型过于简化。

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

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

最新更新