由于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?
因为函数参数的顶级常量是函数的实现细节.例如,以下内容有效:
// 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 *不是.
| 归档时间: |
|
| 查看次数: |
365 次 |
| 最近记录: |