我構建一個簡單的容器類,但碰到一些問題(重裝在Visual C++ 2010, rvalue reference bug?的那些)右值,模板的分辨率和拷貝構造函數(在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)) {
}
增加了一個編輯問題 - 爲什麼不是專門的構造函數調用? –
正如我所說。首先,'MD(MF &&)'甚至不會計算,因爲你沒有傳遞右值引用。第二,'MF(const MD&)'失去了針對'T(MF&)'匹配的'MD(T &&)',並且變成了'MD(MF&)'。 (請注意,它是'T'本身就是參考類型,這在'MyType'中不會發生!) –
謝謝!現在我得到了什麼錯誤。此外,它看起來像一個元組類型GCC的創造者和相關的家庭有他們固定與非const同樣的問題(http://gcc.gnu.org/ml/libstdc++/2008-02/msg00047.html)參考構造函數。要按照他們的步驟。 –