这个模板代码在 c++20 中有什么问题

问题描述

模板问题;第一个是包含模板及其定义的头文件,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;
}

我只是无法编译,它在数据成员“(const Pair& other) const = default;”。我已经阅读了关于操作

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)