C++ 如何将一种类型专门化为一个系列?

C++ 如何将一种类型专门化为一个系列?,c++,range,c++20,C++,Range,C++20,我一直在努力使自定义类型符合作为一个范围的要求。在C++标准中,定义了如下范围: template< class T > concept range = requires(T& t) { ranges::begin(t); // equality-preserving for forward iterators ranges::end (t); }; 以下是我使用的代码: // This file is a "Hello, world!" in

我一直在努力使自定义类型符合作为一个范围的要求。在C++标准中,定义了如下范围:

template< class T >
concept range = requires(T& t) {
  ranges::begin(t); // equality-preserving for forward iterators
  ranges::end  (t);
};
以下是我使用的代码:

// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include <ranges>
#include <vector>

struct Foo
{
  std::vector<int> vec;
  
  auto begin() { return vec.begin(); }
  auto end() { return vec.end(); }
  auto cbegin() const { return vec.cbegin(); }
  auto cend() const { return vec.cend(); }
  auto size() const { return vec.size(); }
};

namespace std::ranges
{
  auto begin(Foo& x) { return x.begin(); }
  auto end(Foo& x) { return x.end(); }
  auto cbegin(const Foo& x) { return x.cbegin(); }
  auto cend(const Foo& x) { return x.cend(); }
}

template <std::ranges::range range>
void some_algorithm(const range& r)
{
  for (const auto& x : r)
  {
    std::cout << x << '\n';
  }
}

int main()
{
    auto f = Foo { { 1, 2, 3, 4 } };
    
    some_algorithm(f.vec); // this works!
    //some_algorithm(f); // this doesn't compile!
}
<代码> //此文件是GCC为Wangbox提供的“Hello World!”的C++语言。 #包括 #包括 #包括 #包括 结构Foo { std::vec; 自动开始(){return vec.begin();} 自动结束(){return vec.end();} auto cbegin()常量{return vec.cbegin();} auto cend()常量{return vec.cend();} 自动大小()常量{返回向量大小();} }; 命名空间std::范围 { 自动开始(Foo&x){返回x.begin();} 自动结束(Foo&x){return x.end();} 自动cbegin(constfoo&x){return x.cbegin();} auto-cend(const-Foo&x){return x.cend();} } 模板 无效某些_算法(常数范围&r) { 用于(常数自动和x:r) {
std::cout?没有常量重载。
auto begin()const{something}
和no
auto end()const{something}
等。
// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include <ranges>
#include <vector>

struct Foo
{
  std::vector<int> vec;
  
  auto begin() { return vec.begin(); }
  auto end() { return vec.end(); }
  auto cbegin() const { return vec.cbegin(); }
  auto cend() const { return vec.cend(); }
  auto size() const { return vec.size(); }
};

namespace std::ranges
{
  auto begin(Foo& x) { return x.begin(); }
  auto end(Foo& x) { return x.end(); }
  auto cbegin(const Foo& x) { return x.cbegin(); }
  auto cend(const Foo& x) { return x.cend(); }
}

template <std::ranges::range range>
void some_algorithm(const range& r)
{
  for (const auto& x : r)
  {
    std::cout << x << '\n';
  }
}

int main()
{
    auto f = Foo { { 1, 2, 3, 4 } };
    
    some_algorithm(f.vec); // this works!
    //some_algorithm(f); // this doesn't compile!
}