由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - C++ function template问题
相关主题
各位,我看那些老将小将实在是愚蠢,你们有没有兴趣我们自己搞(转载)jbuilder9 personal, full version free
chase accounts have been closed1GHz 一下的机器跑点什么好?
相关话题的讨论汇总
话题: template话题: int话题: function话题: func话题: c++
进入Programming版参与讨论
1 (共1页)
C***y
发帖数: 2546
1
我有两个function,一个传入pointer,另外一个传入refernce
例如:
void func(int& a);
void func(double* a);
有办法为这两个function写一个function template吗?
Thanks!
X****r
发帖数: 3557
2
That depends on what do you do inside these two functions.

【在 C***y 的大作中提到】
: 我有两个function,一个传入pointer,另外一个传入refernce
: 例如:
: void func(int& a);
: void func(double* a);
: 有办法为这两个function写一个function template吗?
: Thanks!

C***y
发帖数: 2546
3
Inside the functions, code is exactly the same.
I can use overloading, but it will duplicate the code. That's why I was
wondering if I can use template instead.
Thanks!

【在 X****r 的大作中提到】
: That depends on what do you do inside these two functions.
X****r
发帖数: 3557
4
I'm curious how "int&" and "double*" are used exactly the same?
Anyhow, if this is indeed the case, you can write
template void func(T a) {
//...
}
However, note that this may not work as you expected: to invoke
T=int&, you're likely to need to write "func(x)" for int x,
because by default T=int for int x.

【在 C***y 的大作中提到】
: Inside the functions, code is exactly the same.
: I can use overloading, but it will duplicate the code. That's why I was
: wondering if I can use template instead.
: Thanks!

C***y
发帖数: 2546
5
two overloaded functions, one for pointer, another for reference....

【在 X****r 的大作中提到】
: I'm curious how "int&" and "double*" are used exactly the same?
: Anyhow, if this is indeed the case, you can write
: template void func(T a) {
: //...
: }
: However, note that this may not work as you expected: to invoke
: T=int&, you're likely to need to write "func(x)" for int x,
: because by default T=int for int x.

1 (共1页)
进入Programming版参与讨论
相关主题
各位,我看那些老将小将实在是愚蠢,你们有没有兴趣我们自己搞(转载)jbuilder9 personal, full version free
chase accounts have been closed1GHz 一下的机器跑点什么好?
相关话题的讨论汇总
话题: template话题: int话题: function话题: func话题: c++