【发布时间】: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);
}
如何定义允许最后一行编译的构造函数?
当然,对于这个小代码示例,Vector 和 Box 可能有更好的设计,但这里的类型过于简化了。
【问题讨论】:
-
你可能想要类似
template <typename U, std::enable_if_t<std::is_constructible<T, U>::value>* = nullptr> Vector(const std::vector<U>& values); -
完美运行,谢谢。为什么这里的 C++ 专家总是如此谦虚,以至于他们从不将他们的工作建议作为答案发布,而是作为评论发布? :-) 这样做,如果你喜欢
标签: c++ c++11 templates visual-c++ boxing