为什么标准不允许定义下面的两个函数`f`?

Mao*_*Mao 1 c++ templates c++11

§14.8.2/ 4允许实例化两个不同的函数,g<int>g<const int>从模板定义中实现.为什么标准不允许在f下面的代码中定义这两个函数?我知道两个函数都有相同的类型void(int).但这也发生在实例化的函数中g.§14.8.2/ 4中的注释说:f<int>(1) and f<const int>(1) call distinct functions even though both of the functions called have the same function type..

#include <iostream>

template<typename T>
void g(T t) { std::cout << t << '\n'; }

void f(int i) { std::cout << i << '\n'; }
//void f(int const i) { std::cout << i << '\n'; }   // doesn't compile

int main()
{
    g<int>(1);
    g<int const>(2);
} 
Run Code Online (Sandbox Code Playgroud)

Pra*_*ian 5

const参数类型的顶级s不是函数签名的一部分.因此f(),就过载分辨率而言,您定义的两个版本具有相同的功能,使第二个版本成为重新定义.

来自§13.1/ 3 [over.load]

- 参数声明仅在存在或不存在const和/或volatile等效时有所不同.也就是说,在确定声明,定义或调用哪个函数时,将忽略每个参数类型constvolatile类型说明符.[ 例如:

 typedef const int cInt;
 int f (int);
 int f (const int); // redeclaration of f(int)
 int f (int) { /* ... */ } // definition of f(int)
 int f (cInt) { /* ... */ } // error: redefinition of f(int)
Run Code Online (Sandbox Code Playgroud)

-end example] 以这种方式只忽略参数类型规范最外层
constvolatile类型说明符 ; constvolatile掩埋的参数类型规范内型说明符显著,并且可以用来区分重载函数声明.