【问题标题】:C++: Construct a vector of Box types from vector of boxed elementsC ++:从装箱元素的向量构造一个Box类型的向量
【发布时间】:2017-05-10 17:59:54
【问题描述】:

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

#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 &lt;typename U, std::enable_if_t&lt;std::is_constructible&lt;T, U&gt;::value&gt;* = nullptr&gt; Vector(const std::vector&lt;U&gt;&amp; values);
  • 完美运行,谢谢。为什么这里的 C++ 专家总是如此谦虚,以至于他们从不将他们的工作建议作为答案发布,而是作为评论发布? :-) 这样做,如果你喜欢

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多