c++ - 如何专门化 std::begin?

标签 c++ templates c++11 template-specialization template-function

我正在尝试为自定义容器专门化 std::begin。我这样做是因为我想对容器使用基于范围的 for。这是我的:

class stackiterator { … };
class stack { … };

#include <iterator>

template <> stackiterator std::begin(stack& S)
{
  return S.GetBottom();
}

我在 begin 特化的定义中遇到以下错误:

No function template matches function template specialization 'begin'

我做错了什么?

最佳答案

I'm trying to specialize std::begin for a custom container. I'm doing this because I want to use range-based for with the container.

你找错人了。基于范围的 for 根本不使用 std::begin。对于类类型,编译器直接查找成员 beginend,如果两者都没有找到,则免费进行仅 ADL 查找 beginend 在关联的命名空间中。不执行普通的不合格查找;如果您的类不在 std 命名空间中,则无法获取 std::begin

即使你想做的特化是可能的(除非你引入一个成员 begin() - 一个函数模板的显式特化不能改变返回类型,并且有问题的重载返回“任何成员 begin() 返回”;如果你确实引入了一个成员 begin(),你为什么要专门化 std::begin 来做它本来应该做的事情?),你仍然无法将它与基于范围的 for 一起使用。

关于c++ - 如何专门化 std::begin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31445809/

相关文章:

c++ - 您可以使用类型信息查找类型吗?

c++ - 理解旋转 N x N 矩阵的逻辑

c++ - C++ 中的模板和高阶种类

c++ - 在具有通用引用参数的函数模板中使用类模板

c++ - 如何在 Mac OS X 上使用 gdb 打印出 vector<unique_ptr> 中的内容

c++ - 如何解决这个歧义?

c++ - 为没有继承的模板参数类提供构造函数

c++ - 比较和交换 : synchronizing via different data sizes

c++ - 三元运算符 vs if 语句 : compiler optimization

c++ - 制作模板功能区分继承人和他人