#include <string>
#include <vector>
template<typename T>
class Box {
public:
Box(const T& value) : _value(value) {};
private:
T _value;
/* ... */
};
typedef Box<int> Int;
typedef Box<double> Double;
typedef Box<std::string> String;
int main(int argc, char* argv[]) {
String a("abc");
std::vector<String> b = { std::string("abc"), std::string("def") };
// error C2664: 'Box<std::string>::Box(const Box<std::string> &)' : cannot convert argument 1 from 'const char' to 'const std::string &'
std::vector<String> c = { "abc", "def" };
}
虽然a
和b
可以编译,但c
不能编译,原因似乎是我试图从const char
初始化。这引发了两个问题:
为什么
b
可以而c
不行?是因为std::vector<Box<std::string> >
中的嵌套模板吗?我能否使
c
正常工作而不破坏通用装箱机制(参见typedef Box<double> Double
)?
String a = "abc";
``(编译器的错误消息可能会有所不同,但错误是相同的)。也许错误在于您不能使用隐式转换(通过调用构造函数或使用用户定义的强制类型转换运算符)与模板一起使用? - nefas