0
我是模板編碼的初學者,並且無法在模板中定義構造函數,只是查找有關該問題的答案,但無法找到相關問題。在模板中定義複製構造函數
基本上類/結構xpair
類似於pair
它有first
和second
。
template <typename First, typename Second>
struct xpair {
First first{};
Second second{};
xpair(){}
xpair (const First& first, const Second& second):
first(first), second(second) {}
xpair& operator() (const First& first_, const Second& second_) {
return new xpair (first_, second_);
}
xpair& operator= (const xpair& that) {
return new xpair (that.first, that.second);
}
};
當我試着寫類似
xpair<string, string> a, b;
a = b;
它給誤差
non-const lvalue reference to type
'xpair<std::__1::basic_string<char>, std::__1::basic_string<char> >'
cannot bind to a temporary of type 'xpair<std::__1::basic_string<char>,
std::__1::basic_string<char> > *'
我試圖重寫
return new xpair (that.first, that.second);
到
return new pair (const_cast<First&>(that.first), const_cast<First&>(that.second));
但它不起作用。問題在哪裏?