模板问题;第一个是包含模板及其定义的头文件,Visual Studio 2019 没有显示 /C++lastest 功能(c++20)的警告
#ifndef PAIR_H
#define PAIR_H
#include <compare>
#include <iostream>
template <typename First, typename Second>
class Pair
{
public:
// Public members + no m_ prefix analogous to std::pair<> (see <utility> module)
First first;
Second second;
Pair() = default;
Pair(const First& f, const Second& s);
// Note: not all compiler may fully support this generation yet (C++20)...
// (replacing auto with std::strong_ordering may make Soln17_02.cpp compile then,
// but in general auto is better because First and/or Second could be types
// that are not strongly ordered, such as a floating-point types)
auto operator<=>(const Pair& other) const = default;
};
// Constructor
template <typename First, typename Second>
Pair<First, Second>::Pair(const First& f, const Second& s)
: first{f}, second{s}
{}
template <typename First, typename Second>
std::ostream& operator<<(std::ostream& out, const Pair<First, Second>& pair)
{
return out << '(' << pair.first << ", " << pair.second << ')';
}
#endif
波纹管只是解决方案
#include "Pair.h"
#include <iostream>
#include <string>
int main()
{
// To make the s string literal suffix work
// (facilitates creation of Pairs using CTAD, or Constructor Template Argument Deduction).
// This syntactic sugar for creating std::string objects is not really covered in the book.
using namespace std::string_literals;
auto my_pair{ Pair{122, "abc"s} };
++my_pair.first;
std::cout << "my_pair equals " << my_pair << std::endl;
auto pair1{ Pair{ 0, "def"s} };
auto pair2{ Pair{123, "abc"s} };
auto pair3{ Pair{123, "def"s} };
std::cout << (pair1 < pair2 && pair2 < pair3? "operator< seems to be working" : "oops") << std::endl;
std::cout << (pair1 == pair2? "oops" : "operator== works as well") << std::endl;
}
我只是无法编译,它显示了这个“错误 C2098 数据成员 '<=' 后的意外令牌”,它指向这一行“auto operator<=>(const Pair& other) const = default;”。我已经阅读了有关操作的 cpp++ 参考<<。是模板错误还是有什么问题?谢谢