c++ - C++ 标准中 14.8.2 第 3 段和第 4 段的含义是什么?

标签 c++ templates c++11

我很难理解这条规则,特别是下面加粗的句子(我的重点):

考虑下面代码片段中的注释 #2:函数类型是 f(int) 是什么意思? ,但是 tconst

§14.8.2/3:

After this substitution is performed, the function parameter type adjustments described in 8.3.5 are performed. [ Example: A parameter type of “void ()(const int, int[5])” becomes “void(*)(int,int*)”. —end example ] [ Note: A top-level qualifier in a function parameter declaration does not affect the function type but still affects the type of the function parameter variable within the function. —end note ] [ Example:

template <class T> void f(T t);
template <class X> void g(const X x);
template <class Z> void h(Z, Z*);
int main() {
    // #1: function type is f(int), t is non const
    f<int>(1);
    // #2: function type is f(int), t is const
    f<const int>(1);
    // #3: function type is g(int), x is const
    g<int>(1);
    // #4: function type is g(int), x is const
    g<const int>(1);
    // #5: function type is h(int, const int*)
    h<const int>(1,0);

}

—end example ]

§14.8.2/4:

[ Note: f<int>(1) and f<const int>(1) call distinct functions even though both of the functions called have the same function type. —end note ]

最佳答案

考虑:

template <class T> void f(T t) { t = 5; }

f<int>格式正确,但是 f<const int>不是,因为它试图分配给 const变量。

参见:Use of 'const' for function parameters

关于c++ - C++ 标准中 14.8.2 第 3 段和第 4 段的含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24617413/

相关文章:

C++ Win32 监听全局键绑定(bind)

c++ - 通过枚举重载模板化成员函数

C++11 'native_handle' 不是 'std::this_thread' 的成员

c++ - 警告 : non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]

c++ - 移动构造函数是自动生成的吗?

c++ - 提升几何圆段相交

c++ - 使用 std::reverse 反转 vector 前几个元素的顺序

C++:将 const 与模板参数组合

c++ - 使用模板类时没有合适的默认构造函数可用

c++ - 编译器会为 ref 参数实例化一个新的模板函数吗?