忽略了部分函数特化中值类型的顶级const限定符

hhb*_*lly 1 c++ c++11

由于const int专业化导致以下错误:

#include <iostream>
using std::cout;
using std::endl;

template <typename T> void g(T val)
{
    cout << "unknown" << endl;
}

template <> void g(int && val)
{
    cout << "int &&" << endl;
}

template <> void g(const int && val)
{
    cout << "const int &&" << endl;
}

template <> void g(int & val)
{
    cout << "int &" << endl;
}

template <> void g(const int & val)
{
    cout << "const int &" << endl;
}

template <> void g(int val)
{
    cout << "int" << endl;
}

template <> void g(const int val)  //redefinition here
{
    cout << "const int" << endl;
}

int main() {}

error: redefinition of 'g'
template <> void g(const int val)
                 ^
Run Code Online (Sandbox Code Playgroud)

为什么T&T&&不同于const T&const T&&,但T不显着的const T

cdh*_*wie 6

因为函数参数的顶级常量是函数的实现细节.例如,以下内容有效:

// Prototype
void foo(int c);

// Implementation
void foo(int const c) { ... }
Run Code Online (Sandbox Code Playgroud)

由于参数是通过值传递的,因此调用者并不关心函数是否要修改自己的私有副本.因此,顶级常量不是函数签名的一部分.

请注意,这仅适用于顶级常量! int并且int const在函数原型中是等价的,就像int *int * const.但int *int const *不是.