c++ - 将局部变量分类为 C++11 之前的谓词

标签 c++ c++11 compiler-errors language-lawyer predicate

以下代码在使用 GCC 和 Clang 以 C++11 模式构建时编译时没有错误/警告。但是,如果我尝试在没有 C++11 模式的情况下进行编译,并且在第二个范围内发生错误。

#include <algorithm>
#include <vector>

struct astruct
{
   int v;
};

struct astruct_cmp0
{
   bool operator()(const astruct& a0, const astruct& a1) {
     return a0.v < a1.v;
   }
};

int main()
{
   std::vector<astruct> alist;
   {
      // Works - no errors
      std::stable_sort(alist.begin(),alist.end(),astruct_cmp0());
   }

   {
      struct astruct_cmp1
      {
         bool operator()(const astruct& a0, const astruct& a1) {
           return a0.v < a1.v;
         }
      };

      // error: template argument uses local type 'astruct_cmp1'
      std::stable_sort(alist.begin(),alist.end(),astruct_cmp1());
   }

   return 0;
}

我的问题是:允许本地结构定义的 C++11 更改是什么?有人可以指出标准中的特定部分吗(也许是第 9.8 节?)

最佳答案

在 C++03 中,函数局部类型不是可行的模板参数。在 C++11 函数中,局部类型是可行的模板参数。 C++03 中的关键引用是 14.3.1 [temp.arg.type] 第 2 段:

The following types shall not be used as a template-argument for a template type-parameter:

  • a type whose name has no linkage
  • ...

在 C++11 中,此约束已被删除。

关于何时定义链接的相关部分是 3.5 [basic.link](在两个标准中),它相当长并且指向没有通过排除链接的实体,C++03 中的第 8 段:

Names not covered by these rules have no linkage. ...

函数内定义的类型未在“这些规则”中列出。

关于c++ - 将局部变量分类为 C++11 之前的谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26749011/

相关文章:

c++ - 为什么编译器不能将 const int 绑定(bind)到右值引用?

std::vector 的 C++ 钳位函数

通用图像处理库的 C# 设计指南

c++ - Visual Studio : how to start up a project without the console window poping up

c++ - 在 C++ std::vector 之外的线程中启动可运行对象

C 函数 fopen();错误: too many arguments to the function

java - <identifier> 预期错误。无法解决它

regex - 使用正则表达式模式会产生编译错误 “Invalid regular expression”

c++ - 如何使用 clang 前端获取 asm 语句的位置

c++ - 越界访问数组不会出错,为什么?