473,698 Members | 1,884 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pass-by-reference for template?

Hello,

I learned that when I work with templates in C++, I should have
functions that pass arguments by reference because the type of object
is not known. Does it mean that if I have a function that is template
function, then it's argument should be a reference type, such as the
following?

template<class T>
void f(T& t){...}

What if I replace the signature by

template<class T>
void f(T t){...}

or

template<class T>
void f(T* tp){...}

Would it work and if not, could someone tell me why please?

Thanks,
Jess

Aug 20 '07 #1
7 5886
"Jess" <wd***@hotmail. comwrote in message
news:11******** *************@x 35g2000prf.goog legroups.com...
Hello,

I learned that when I work with templates in C++, I should have
functions that pass arguments by reference because the type of object
is not known. Does it mean that if I have a function that is template
function, then it's argument should be a reference type, such as the
following?

template<class T>
void f(T& t){...}

What if I replace the signature by

template<class T>
void f(T t){...}

or

template<class T>
void f(T* tp){...}

Would it work and if not, could someone tell me why please?
It would work the same way a function would work. So, yes, it would work
the because
void f(int* tp) {/*...*/}
would work.
Aug 20 '07 #2
On 2007-08-20 15:52, Jess wrote:
Hello,

I learned that when I work with templates in C++, I should have
functions that pass arguments by reference because the type of object
is not known. Does it mean that if I have a function that is template
function, then it's argument should be a reference type, such as the
following?
I don't see much connection between templates and using references. In
general, using references is often better than passing by value, whether
you are using templates or not, since it requires less copying.
template<class T>
void f(T& t){...}

What if I replace the signature by

template<class T>
void f(T t){...}
The reference version is slightly better since it does not require the
type used to be copyable. While most types are copyable there are
instances where it might be beneficial to disallow copying.
template<class T>
void f(T* tp){...}
When using pointers you always run the risk of someday getting a NULL-
pointer, with references you don't.

--
Erik Wikström
Aug 20 '07 #3
Thanks for your replies. The reason I asked the question is that I
was told to use reference rather the actual value because T is a
template parameter and it's value isn't known until instantiation. Is
this not so? or, is there some other kind of template functions that
require the use of reference rather than the actual type?

Thanks,
Jess

Aug 22 '07 #4
On Aug 21, 12:40 am, "Alf P. Steinbach" <al...@start.no wrote:
* Erik Wikström:
On 2007-08-20 15:52, Jess wrote:
Hello,
I learned that when I work with templates in C++, I should have
functions that pass arguments by reference because the type of object
is not known. Does it mean that if I have a function that is template
function, then it's argument should be a reference type, such as the
following?
I don't see much connection between templates and using references. In
general, using references is often better than passing by value, whether
you are using templates or not, since it requires less copying.
template<class T>
void f(T& t){...}
What if I replace the signature by
template<class T>
void f(T t){...}
The reference version is slightly better since it does not require the
type used to be copyable. While most types are copyable there are
instances where it might be beneficial to disallow copying.

Well. If T is non-const, then

T&

requires an lvalue actual argument (because an rvalue can't be bound to
a reference).

And if T is const, that is, T is mapped to U const, then with the
current standard

U const&

requires U to have an accessible copy constructor.
Do you mean I can use const T& but not T& here? If I have a non-
template function, I can always have both a const-ref version and a
non-const-ref version. Is this not true for template functions?

Thanks,
Jess

Aug 22 '07 #5
On 2007-08-22 14:59, Jess wrote:
Thanks for your replies. The reason I asked the question is that I
was told to use reference rather the actual value because T is a
template parameter and it's value isn't known until instantiation. Is
this not so? or, is there some other kind of template functions that
require the use of reference rather than the actual type?
In the future please quote the text you are replying to.

It's kind of true but irrelevant, templates are instantiated during
compilation so the compiler knows the type when it needs to. In other
words you won't risk getting your classes sliced or such, like you would
with runtime polymorphism.

The fact that a template is involved have nothing do do with the usage
of references, however using references (or const references) is
generally a good idea (even if you don't work with templates) since it
prevents unnecessary copying.

--
Erik Wikström
Aug 22 '07 #6
On 2007-08-22 15:02, Jess wrote:
On Aug 21, 12:40 am, "Alf P. Steinbach" <al...@start.no wrote:
>* Erik Wikström:
On 2007-08-20 15:52, Jess wrote:
Hello,
>I learned that when I work with templates in C++, I should have
functions that pass arguments by reference because the type of object
is not known. Does it mean that if I have a function that is template
function, then it's argument should be a reference type, such as the
following?
I don't see much connection between templates and using references. In
general, using references is often better than passing by value, whether
you are using templates or not, since it requires less copying.
>template<cla ss T>
void f(T& t){...}
>What if I replace the signature by
>template<cla ss T>
void f(T t){...}
The reference version is slightly better since it does not require the
type used to be copyable. While most types are copyable there are
instances where it might be beneficial to disallow copying.

Well. If T is non-const, then

T&

requires an lvalue actual argument (because an rvalue can't be bound to
a reference).

And if T is const, that is, T is mapped to U const, then with the
current standard

U const&

requires U to have an accessible copy constructor.

Do you mean I can use const T& but not T& here? If I have a non-
template function, I can always have both a const-ref version and a
non-const-ref version. Is this not true for template functions?
You can have both const and non-const with templates, the issue has
nothing to do with templates per se, it's just that const ref is the
most flexible way to pass arguments. Consider the following code:

class Foo
{
Foo(const Foo&);
Foo& operator=(const Foo&);
int v;
public:
Foo(int i) : v(i) {}
};

void val(Foo);

void ref(Foo&);

void cref(const Foo&);

int main()
{
Foo f(1);
// [1]
val(f);
ref(f);
cref(f);

// [2]
ref(Foo(1));
cref(Foo(1));
}

The class Foo can not be copied (the copy ctor is private), the three
function each use different ways to pass parameters. If you try to
compile the code you'll notice that the call to val(f) under [1] does
not work. This is because passing by value requires that you can copy
the object passed. IF you comment out that call you'll see that both
ref(f) and cref(f) works.

Next we'll look at the difference between ref and const ref, to do this
comment out the copy ctor in Foo (this will allow the compiler to
generate one). You'll now notice that ref(Foo(1)) does not compiler but
that cref(Foo(1)) does, this is because a const ref can bind to an
r-value while a normal ref can't.

As you can see a const ref is more versatile than a ref, which is more
versatile than passing by value, plus that you don't get the overhead of
copying the object. So if you can using a const ref is usually a good
idea since it will allow usages that ways wont.

--
Erik Wikström
Aug 22 '07 #7
On Aug 23, 12:00 am, Erik Wikström <Erik-wikst...@telia. comwrote:
On 2007-08-22 15:02, Jess wrote:
On Aug 21, 12:40 am, "Alf P. Steinbach" <al...@start.no wrote:
* Erik Wikström:
On 2007-08-20 15:52, Jess wrote:
Hello,
I learned that when I work with templates in C++, I should have
functions that pass arguments by reference because the type of object
is not known. Does it mean that if I have a function that is template
function, then it's argument should be a reference type, such as the
following?
I don't see much connection between templates and using references. In
general, using references is often better than passing by value, whether
you are using templates or not, since it requires less copying.
template<class T>
void f(T& t){...}
What if I replace the signature by
template<class T>
void f(T t){...}
The reference version is slightly better since it does not require the
type used to be copyable. While most types are copyable there are
instances where it might be beneficial to disallow copying.
Well. If T is non-const, then
T&
requires an lvalue actual argument (because an rvalue can't be bound to
a reference).
And if T is const, that is, T is mapped to U const, then with the
current standard
U const&
requires U to have an accessible copy constructor.
Do you mean I can use const T& but not T& here? If I have a non-
template function, I can always have both a const-ref version and a
non-const-ref version. Is this not true for template functions?

You can have both const and non-const with templates, the issue has
nothing to do with templates per se, it's just that const ref is the
most flexible way to pass arguments. Consider the following code:

class Foo
{
Foo(const Foo&);
Foo& operator=(const Foo&);
int v;
public:
Foo(int i) : v(i) {}

};

void val(Foo);

void ref(Foo&);

void cref(const Foo&);

int main()
{
Foo f(1);

// [1]
val(f);
ref(f);
cref(f);

// [2]
ref(Foo(1));
cref(Foo(1));

}

The class Foo can not be copied (the copy ctor is private), the three
function each use different ways to pass parameters. If you try to
compile the code you'll notice that the call to val(f) under [1] does
not work. This is because passing by value requires that you can copy
the object passed. IF you comment out that call you'll see that both
ref(f) and cref(f) works.

Next we'll look at the difference between ref and const ref, to do this
comment out the copy ctor in Foo (this will allow the compiler to
generate one). You'll now notice that ref(Foo(1)) does not compiler but
that cref(Foo(1)) does, this is because a const ref can bind to an
r-value while a normal ref can't.

As you can see a const ref is more versatile than a ref, which is more
versatile than passing by value, plus that you don't get the overhead of
copying the object. So if you can using a const ref is usually a good
idea since it will allow usages that ways wont.
Thanks for the examples and explanations! :)
Jess

Aug 23 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1332
by: uli2003wien | last post by:
Dear group, PASS (SQL-Server user group) is about to start founding a branch in Vienna. I went to SQLCON and met some guys from the German PASS group and decided to become a member of PASS, decided to look for other individuals to take part in an Austrian branch of PASS based in Vienna, so whoever is interested may take a look at http://www.sqlpass.de/Default.aspx?tabid=191 in order to get to contact me to get things going....
8
2610
by: Tcs | last post by:
I've been stumped on this for quite a while. I don't know if it's so simple that I just can't see it, or it's really possible. (Obviously, I HOPE it IS possible.) I'm trying to get my queries to run from VB. My pass-thru query retrieves data from our AS/400 that I use to build a local table (on my PC). My pass-thru and local do in fact work together when I run them interactively. But I want, no make that NEED, to run them from VB. ...
2
17097
by: Alex Nitulescu | last post by:
Hi. I have tried to pass two parameters, like this: Response.Redirect(String.Format("NewPage.aspx?Username={0}, Pass={1}", txtUserName.Text, txtPass.Text)) But if I pass Username="Alex" and Pass="AAA", I get Params("Username") = "alex, Pass=AAA" and Params("Pass")="", which is not what I expected.
3
5482
by: Brett | last post by:
I have several classes that create arrays of data and have certain properties. Call them A thru D classes, which means there are four. I can call certain methods in each class and get back an array of data. All four classes are the same except for the number of elements in their arrays and the data. I have a MainClass (the form), which processes all of these arrays. The MainClass makes use of third party objects to do this. There...
4
2249
by: Marcelo | last post by:
Any suggestion? Thanks Marcelo
3
12595
by: ILCSP | last post by:
Hello, I'm fairly new to the concept of running action pass through queries (insert, update, etc.) from Access 2000. I have a SQL Server 2000 database and I'm using a Access 2K database as my front end. I'm using a blank pass through query which gets the Transact-SQL part inserted from a button in my form. After inserting the Transact-SQL code into the pass through query, I 'open the recordset' to make the query run. However,...
3
2136
by: Ronald S. Cook | last post by:
I want to something as simple as: UserControl uctTemp; But the type will be passed in to the function (which will be an existing user control like "uctMyUserControl1") So, how can I pass in the string "uctMyUserControl1" and then somehow dim an instance of it?
5
6322
by: marshmallowww | last post by:
I have an Access 2000 mde application which uses ADO and pass through queries to communicate with SQL Server 7, 2000 or 2005. Some of my customers, especially those with SQL Server 2005, have had pass-through queries fail due to intermittent connection failures. I can easily restablish a connection for ADO. My problem is with pass-through queries.
5
15624
by: Remote_User | last post by:
Hi, Is there any way I can pass a file as a parameter? ( maybe read it into a object) I am working on C# VS2005. Thanks.
14
3603
by: =?Utf-8?B?Umljaw==?= | last post by:
I have seen examples of passing data from FormB to FormA (Parent To Child) but I need an example of passind data from FormA to FormB. My main form is FormA; I will enter some data in textboxes and click a button to bring up FormB which needs to display values entered in FormA. Thanks in advance.
0
8668
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8597
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9148
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9012
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7708
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4358
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4611
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3034
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2319
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.