我正在构建一个简单的容器类,但遇到了一些问题(重新组装Visual C++ 2010 中的那些,右值引用错误?)
#include <cassert>
#include <utility>
template<typename T0>
class MyType {
public:
typedef T0 value_type;
// Default constructor
MyType() : m_value() {
}
// Element constructor
explicit MyType(const T0 &c_0) : m_value(c_0) {
}
template<typename S0>
explicit MyType(S0 &&c_0) : m_value(std::forward<S0>(c_0)) {
}
// Copy constructor
MyType(const MyType &other) : m_value(other.m_value) {
}
MyType(MyType &&other) : m_value(std::forward<value_type>(other.m_value)) {
}
// Copy constructor (with convertion)
template<typename S0>
MyType(const MyType<S0> &other) : m_value(other.m_value) {
}
template<typename S0>
MyType(MyType<S0> &&other) : m_value(std::move(other.m_value)) {
}
// Assignment operators
MyType &operator=(const MyType &other) {
m_value = other.m_value;
return *this;
}
MyType &operator=(MyType &&other) {
m_value = std::move(other.m_value);
return *this;
}
template<typename S0>
MyType &operator=(const MyType<S0> &other) {
m_value = other.m_value;
return *this;
}
template<typename S0>
MyType &operator=(MyType<S0> &&other) {
m_value = std::move(other.m_value);
return *this;
}
// Value functions
value_type &value() {
return m_value;
}
const value_type &value() const {
return m_value;
}
private:
template<typename S0>
friend class MyType;
value_type m_value;
};
int main(int argc, char **argv) {
MyType<float> t1(5.5f);
MyType<double> t2(t1);
return 0;
}
上面的代码给出了以下错误:
1>ClCompile:
1> BehaviorIsolation.cpp
1>behaviorisolation.cpp(18): error C2440: 'initializing' : cannot convert from 'MyType<T0>' to 'double'
1> with
1> [
1> T0=float
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1> behaviorisolation.cpp(78) : see reference to function template instantiation 'MyType<T0>::MyType<MyType<float>&>(S0)' being compiled
1> with
1> [
1> T0=double,
1> S0=MyType<float> &
1> ]
1>behaviorisolation.cpp(18): error C2439: 'MyType<T0>::m_value' : member could not be initialized
1> with
1> [
1> T0=double
1> ]
1> behaviorisolation.cpp(73) : see declaration of 'MyType<T0>::m_value'
1> with
1> [
1> T0=double
1> ]
1>
1>Build FAILED.
如何在不使用链接问题中描述的技巧的情况下纠正此错误?
谢谢!
编辑: 最让我困惑的是为什么没有调用两个专门的构造函数。他们更适合通话。
// Copy constructor (with convertion)
template<typename S0>
MyType(const MyType<S0> &other) : m_value(other.m_value) {
}
template<typename S0>
MyType(MyType<S0> &&other) : m_value(std::move(other.m_value)) {
}