#include <string>
#include <tuple>
#include <stdexcept>
using namespace std;
class Date
{
public:
Date() {};
Date(int new_year, int new_month, int new_day)
{
year = new_year;
if ((new_month < 1) || (new_month > 12))
{
throw runtime_error("Month value is invalid: " to_string(new_month));
}
month = new_month;
if ((new_day < 1) || (new_day > 31))
{
throw runtime_error("Day value is invalid: " to_string(new_day));
}
day = new_day;
}
int GetYear() const
{
return year;
}
int GetMonth() const
{
return month;
}
int GetDay() const
{
return day;
}
private:
int year;
int month;
int day;
};
bool operator < (const Date &lhs, const Date &rhs)
{
auto lhs = tie(lhs.GetYear(), lhs.GetMonth(), lhs.GetDay());
auto rhs = tie(rhs.GetYear(), rhs.GetMonth(), rhs.GetDay());
return lhs < rhs;
}
我正在嘗試創建一個用于存盤日期(年、月、日)的類。為了在地圖中使用這個類,我想多載比較運算子。不幸的是,上面的代碼不起作用。編譯器給我一個錯誤
error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'|
錯誤顯然發生在tie函式中。一旦我將其更改為make_tuple所有編譯和作業。我還檢查了我是否宣告了變數year,month并且day作為公共我可以寫一些類似的東西
auto lhs = tie(lhs.year, lhs.month, lhs.day);
這也行。
我不明白為什么。有沒有人有想法?
uj5u.com熱心網友回復:
您的成員函式回傳成員的副本(又名臨時rvalue),并std::tie具有引數串列,該串列嘗試通過非成本左值 ref進行系結。
template< class... Types >
constexpr std::tuple<Types&...> tie( Types&... args ) noexcept;
// ^^^^^^^^^^^^^^^^
根據標準,這根本不可能,因此出現錯誤!
在std::make_tuple另一方面,有轉發參考。因此,沒有問題。
template< class... Types >
std::tuple<VTypes...> make_tuple( Types&&... args );
// ^^^^^^^^^^^^^^^^
當成員是 public 時,它們就變成了左值。
我建議,operator<改為成為班級的朋友。
class Date
{
public:
// .... other code
friend bool operator<(const Date& lhs, const Date& rhs) noexcept
{
return std::tie(lhs.year, lhs.month, lhs.day) < std::tie(rhs.year, rhs.month, rhs.day);
}
private:
int year;
int month;
int day;
};
uj5u.com熱心網友回復:
std::tie的全部目的是創建一個左值參考的元組。您的成員函式回傳int的不是左值,因此您會收到錯誤訊息。
公開成員變數并直接將它們用作引數來tie作業,因為變數是左值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368062.html
