模板简单问题

OOPhaisky 2006-11-02 04:54:26
首先说明一下:
void test(const const int);
这样声明肯定是错误的。

现在我们看看下面的这个模板:
template <class T>
void test(const T a){//注意此处有一个const
...
}
test<const int>(4);//注意实例化类型中还有一个const
此处T应该被实例化为const int,那么test模板函数的实例化结果就会出现两个const的情形:
void test(const const int);
既然这种声明方式是非法的,那为什么编译器允许上述程序顺利通过编译呢?

附:编译环境GCC version 3.2.3。
...全文
256 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
OOPhaisky 2006-11-03
  • 打赏
  • 举报
回复
to lann64(昆仑大鹏) :

const const和& &这种情况在模版中这种使用都是特例。
--------------------------------------------------------------------------
“& &”也是特例么?我好像试验过,“& &”不可以,编译报错。
sinall 2006-11-03
  • 打赏
  • 举报
回复
^_^,楼主好问题。
学习了,前些天我似乎也遇到了该问题,没有细想,反正能用嘛。
lann64 2006-11-03
  • 打赏
  • 举报
回复
可能是标准修改了,编译器实现还没修改吧。
lann64 2006-11-03
  • 打赏
  • 举报
回复
15.2.3 References and Qualifiers

Consider the following function template definition:

// traits/apply1.hpp

template <typename T>
void apply (T& arg, void (*func)(T))
{
func(arg);
}
Consider also the following code that attempts to use it:

// traits/apply1.cpp

#include <iostream>
#include "apply1.hpp"

void incr (int& a)
{
++a;
}

void print (int a)
{
std::cout << a << std::endl;
}

int main()
{
intx=7;
apply (x, print);
apply (x, incr);
}
The call

apply (x, print)
is fine. With T substituted by int, the parameter types of apply() are int& and void(*)(int), which corresponds to the types of the arguments. The call

apply (x, incr)
is less straightforward. Matching the second parameter requires T to be substituted with int&, and this implies that the first parameter type is int& &, which ordinarily is not a legal C++ type. Indeed, the original C++ standard ruled this an invalid substitution, but because of examples like this, a later technical corrigendum (a set of small corrections of the standard; see [Standard02]) made T& with T substituted by int& equivalent to int&. [7]

[7] Note that we still cannot write int& &. This is similar to the fact that T const allows T to be substituted with int const, but an explicit int const const is not valid.

lann64 2006-11-02
  • 打赏
  • 举报
回复
c++templates说
const const和& &这种情况在模版中这种使用都是特例。
jixingzhong 2006-11-02
  • 打赏
  • 举报
回复
就是一种特殊行为,
没有什么原理,
楼主记住这么个处理原则就是了 ...

对于模板,
const 可以修饰模板参数,
即是模板参数本身已经具有const 属性 ...
xiao_potato 2006-11-02
  • 打赏
  • 举报
回复
学习中
cunsh 2006-11-02
  • 打赏
  • 举报
回复
<<c++templates全览>> 15.2.3节 References(引用)和Qualifiers(饰词)

书上说即使某个template parameter被"本身已是const"的某个type替换.c++也允许我们将const饰词施行于该template parameter身上. 因此无论我们怎么用const.都无需操心是否需要剥除const饰词.
pongba 2006-11-02
  • 打赏
  • 举报
回复
因为顶层的const修饰并不会对函数类型产生任何贡献,而只会限制函数内部对该参数的使用。
void f(const int)的类型是 void (int)

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧