c ++ 11 — 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);
}

Как определить конструктор, который позволяет скомпилировать последнюю строку?

Конечно, для этого небольшого примера кода могут быть лучшие проекты для Vector а также Box но типы здесь слишком упрощены.

1

Решение

Вы можете добавить конструктор шаблона:

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

Другие решения

Других решений пока нет …