473,729 Members | 2,083 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Templates, friends, operators .. what more do we need to have fun?

Hello there,

I think I've run into some classic c++ pitfall and maybe some of
you guys can help me out.
For my project I will need to use matrices and vectors and so I
decided to implement them by myself. I know there are already
tons of vector and matrix implementations , but I wanted to have
one taylored for my needs and without debugging someones
else code. Also is's become somewhat personal meanwhile ;-).

The plan :
- define a Matrix<T> and a Vector<T> class
- make them friends to perform some operations directly - quick
and dirty
- define the operators processing instances of more than one type
as friends

After a while and learning a lot about c++ syntax subtleness I made
the first two steps.
Now the linker (I'm using g++ 3.3.4 without any switches refering
templates) is nagging with complaints about not knowing the friend
operators I've defined.

Lets come to the details :

I've defined both classes separated into a header and the
implementation
and for all my template classes I'm using a single .cpp file which
includes
the class template implementations to explicitly instantiate the
specialized classes.

Both header files (matrix and vector) include each other. They contain
- the forward declarations of the class templates
- the operators prototypes
- the class template itself
- including the references to friend classes and friend operators

The operators are defined in the according class implementation files.

Some more details - I will show it exemplarily :

Vector.h
=============== =============== =============== =============== =======
....

#include "Grid2D.h"
#include "Matrix.h"

namespace calcapp {

//a template method
template <class T> void doWhateveryouwa nt(const T& v);

//forward declaration of class template
template <class T> class Vector;
template <class T> class Matrix;

//operator prototypes
template <class T> Matrix<T> operator/ (const Vector<T>& v1, const
Vector<T>& v2);
....

//prototype of a test-method
template <class T> Vector<T> doNothing(const Vector<T>& v);

template <class T>
class Vector : public calcapp::Grid2D <T> {
public:
template <class TF> friend class Matrix;

Vector(int count_dim);
Vector(const Vector & other);

....
//tensor product
friend Matrix<T> operator/<T> (const Vector<T>& v1, const Vector<T>&
v2);
//dummy
friend Vector<T> doNothingInNS<T >(const Vector<T>& v);
protected:
....
}; //class

} //namespace

Vector.cpp
=============== =============== =============== =============== =======
#include "Vector.h"

....
namespace calcapp {

template <class T>
Matrix<T> calcapp::operat or/ (const Vector<T>& v1, const Vector<T>& v2)
{

Matrix<T> result(v1.size_ x, v2.size_x);
....
return result;
} //tensorproduct
....
} //namespace
TemplateInstanc es.cpp
=============== =============== =============== =============== =======
#include "global.h"
#include "Vector.cpp "

namespace calcapp {

template class Grid2D<fptype>;

template class Matrix<fptype>;
template class Matrix<int32>;
template class Matrix<int64>;

template class Vector<fptype>;
template class Vector<int32>;
template class Vector<int64>;

}

test.cpp
=============== =============== =============== =============== =======
....

Vector<fptype) v1(3), v2(3);
....

Matrix<fptype> M = v1/v2;
and here the compiler states :
../RunTest/test.cpp:310: undefined reference to `calcapp::Matri x<double> >calcapp::opera tor/<double>(calcap p::Vector<doubl e> const&, calcapp::Vector <double> const&)'
....
=============== =============== =============== =============== =======
So what the #!@* is wrong? That was obviously a linker error and for my
understanding the compiler didn't generate code for operator/<fptype>.
Correct?

--------------------------
The problem doesn't seem to be about operators because

....
v2 = calcapp::doNoth ing(v1);
....

would leed to an equivalent reaction.
--------------------------
And even

....
int i = 10;
doWhateveryouwa nt(i);
....

won't compile (link) :undefined reference to `void calcapp::doWhat everyouwant<int >(int const&)'


So it seems it has nothing to do with classes or friends either.
But still somehow the linker figured out that the function was defined
in
the namespace calcapp.
--------------------------

Do I have to explicitly instantiate template methods too? I've
read nothing about that so far. How??
Operators?

Ok guys, what's the simple trick? ;-)
bye, Micha

Sep 26 '05 #1
11 2599
Micha wrote:
Hello there,

I think I've run into some classic c++ pitfall and maybe some of
you guys can help me out.
For my project I will need to use matrices and vectors and so I
decided to implement them by myself. I know there are already
tons of vector and matrix implementations , but I wanted to have
one taylored for my needs and without debugging someones
else code. Also is's become somewhat personal meanwhile ;-).

The plan :
- define a Matrix<T> and a Vector<T> class
- make them friends to perform some operations directly - quick
and dirty
- define the operators processing instances of more than one type
as friends

After a while and learning a lot about c++ syntax subtleness I made
the first two steps.
Now the linker (I'm using g++ 3.3.4 without any switches refering
templates) is nagging with complaints about not knowing the friend
operators I've defined.


To be perfectly honest I haven't read all your post (bit too long for
me) but you might care to check the FAQ. It does at least describe a
problem with similar symptoms to yours.

http://www.parashift.com/c++-faq-lit...html#faq-35.10

john
Sep 26 '05 #2
Micha wrote:
Hello there,

I think I've run into some classic c++ pitfall and maybe some of
you guys can help me out.
For my project I will need to use matrices and vectors and so I
decided to implement them by myself. I know there are already
tons of vector and matrix implementations , but I wanted to have
one taylored for my needs and without debugging someones
else code. Also is's become somewhat personal meanwhile ;-).

The plan :
- define a Matrix<T> and a Vector<T> class
- make them friends to perform some operations directly - quick
and dirty
- define the operators processing instances of more than one type
as friends

After a while and learning a lot about c++ syntax subtleness I made
the first two steps.
Now the linker (I'm using g++ 3.3.4 without any switches refering
templates) is nagging with complaints about not knowing the friend
operators I've defined.
....
Some more details - I will show it exemplarily :

Vector.h
First it's a not a good idea to have a header called "vector.h" since
there is an (obsolete) header with the same name in the system include
paths. It seems safer to minimize confusio by renaming it with a less
generic name.


Vector.cpp
=============== =============== =============== =============== =======
#include "Vector.h"

...
namespace calcapp {

template <class T>
Matrix<T> calcapp::operat or/ (const Vector<T>& v1, const Vector<T>& v2)
{

Matrix<T> result(v1.size_ x, v2.size_x);
...
return result;
} //tensorproduct
...
} //namespace
TemplateInstanc es.cpp
It looks like this template function is being defined in a source file.
Template definitions need to be placed in header files so the compiler
will have seen the template defnition before it compiles source code
that instantiates the template. With the template definition in a
source file, it is effectively available only to other routines in this
file which come after it.
#include "global.h"
#include "Vector.cpp "

namespace calcapp {

template class Grid2D<fptype>;

template class Matrix<fptype>;
template class Matrix<int32>;
template class Matrix<int64>;

template class Vector<fptype>;
template class Vector<int32>;
template class Vector<int64>;

}

test.cpp
=============== =============== =============== =============== =======
...

Vector<fptype) v1(3), v2(3);
...

Matrix<fptype> M = v1/v2;
and here the compiler states :
../RunTest/test.cpp:310: undefined reference to `calcapp::Matri x<double> >calcapp::opera tor/<double>(calcap p::Vector<doubl e> const&, calcapp::Vector <double> const&)'


...
=============== =============== =============== =============== =======
So what the #!@* is wrong? That was obviously a linker error and for my
understanding the compiler didn't generate code for operator/<fptype>.
Correct?


When compiling test.cpp, the compiler did not see the definition for
the operator/ by the time it reached line 310 that references it.
Without a definition on hand, the compiler does not know what code to
generate. Nor does the compiler "remember" template definitions from
one source file to the next. Every source file that instantiates a
template must ensure that the the template definition is included
before its own code when it is compiled.

The solution is to move the operator/ template and any other template
definitions into a header file that test.cpp and other clients of these
template classes will then include.

Greg

Sep 27 '05 #3
>
It looks like this template function is being defined in a source file.
Template definitions need to be placed in header files so the compiler
will have seen the template defnition before it compiles source code
that instantiates the template. With the template definition in a
source file, it is effectively available only to other routines in this
file which come after it.

#include "global.h"
#include "Vector.cpp "


Greg, you missed that he wrote #include "Vector.cpp ". Why some people
insist on putting template code in cpp files and then pulling all sorts
of tricks to compensate for this is beyond me.

john
Sep 27 '05 #4
John Harrison wrote:

It looks like this template function is being defined in a source file.
Template definitions need to be placed in header files so the compiler
will have seen the template defnition before it compiles source code
that instantiates the template. With the template definition in a
source file, it is effectively available only to other routines in this
file which come after it.

#include "global.h"
#include "Vector.cpp "


Greg, you missed that he wrote #include "Vector.cpp ". Why some people
insist on putting template code in cpp files and then pulling all sorts
of tricks to compensate for this is beyond me.

john


You're right. Though actually I did notice that #include at one point,
but I lost track of it in that ocean of code.

But it is worth mentioning nonetheless that source files #including
other source files is bad form. Such nested source listings can confuse
the debugger, the programmer, the compiler - and programming is
confusing enough as it is, we need not invent ways to make it more so.

Greg

Sep 27 '05 #5
As far as I got it, the idea is to have the compiler
generate the code for the specialized template classes
once only in the resulting TemplateInstanc es.o object
file.

Wouldn't implementing the whole template class in the
header file, force the compiler to instantiate the same
MyTemplateClass <MyType> class in every object file
generated from any .cpp file in which
MyTemplateClass <MyType> is used?

Btw thanks for your replies but I didn't get any further. My
classes work just fine until I try to use those friend operators.

The template classes which where instantiated in that .cpp
file which includes the .cpp files of the template classes
(together with their header files) get compiled and linked. I can
use their member operators.

As far as I figured it out until now, the problem is that the compiler
won't generate code for the operators despite seeing instantiations of
the template classes they are friends with.

Maybe I can solve my problem if I get the following example to work.

foo_templatestu ff.h
=============== =============== ======
#ifndef FOO_TEMPLATESTU FF_
#define FOO_TEMPLATESTU FF_

template <class T>
void doSomething(T x);
#endif
foo_templatestu ff.cpp
=============== =============== ======
#include "foo_templatest uff.h"
#include <iostream>

template <class T>
void doSomething(T x) {
std::cout << x;
}

main.cpp
=============== =============== ======
#include "foo_templatest uff.h"

int main(int argc, char *argv[]) {

int i = 23;
doSomething(i);

return EXIT_SUCCESS;
}

Again the compiler figures out that it is
void doSomething<int >(int) that should be called while
processing main.cpp, but it didn't see a reason to instantiate that
function while processing foo_templatestu ff.cpp.

Is there no other way but to define the whole function template
in the header file instead of the prototype only?

Ok, there is simple but dirty solution by adding a function
void __dummy__() {
doSomething<int >(5);
}
to foo_templatestu ff.cpp.

It works but I don't like it. I don't want to write some dummy function
that touches all my operator templates for any specialization just to
make that *#!!$ compiler generate the accordant code.

There must be a better way ;-) ! Am I right?

bye, Micha

Sep 27 '05 #6
Micha wrote:
As far as I got it, the idea is to have the compiler
generate the code for the specialized template classes
once only in the resulting TemplateInstanc es.o object
file.

Wouldn't implementing the whole template class in the
header file, force the compiler to instantiate the same
MyTemplateClass <MyType> class in every object file
generated from any .cpp file in which
MyTemplateClass <MyType> is used?
Yes. In fact all of the STL container classes being templates are
entirely implemented in header files <vector>, <list> and so on have to
be included by any code that uses a std::vector, std::list and so
forth. The compiler will instantiate only the methods and templates
that a source file needs. And the linker discards duplicate template
instantiations across files when the program is linked.

In theory, instantiating the templates in a source file would speed up
compile times. But the program would then have to anticipate all of the
instantiations needed in other files. In the end, the same routines end
up in the app anyway, so it's easier to let compiler and linker handle
it.
Btw thanks for your replies but I didn't get any further. My
classes work just fine until I try to use those friend operators.

The template classes which where instantiated in that .cpp
file which includes the .cpp files of the template classes
(together with their header files) get compiled and linked. I can
use their member operators.

As far as I figured it out until now, the problem is that the compiler
won't generate code for the operators despite seeing instantiations of
the template classes they are friends with.
Declaring a template class or function a friend is not enough to
instantiate it, so this behavior is as expected.
Maybe I can solve my problem if I get the following example to work.

foo_templatestu ff.h
=============== =============== ======
#ifndef FOO_TEMPLATESTU FF_
#define FOO_TEMPLATESTU FF_

template <class T>
void doSomething(T x);
#endif
foo_templatestu ff.cpp
=============== =============== ======
#include "foo_templatest uff.h"
#include <iostream>

template <class T>
void doSomething(T x) {
std::cout << x;
}

main.cpp
=============== =============== ======
#include "foo_templatest uff.h"

int main(int argc, char *argv[]) {

int i = 23;
doSomething(i);

return EXIT_SUCCESS;
}

Again the compiler figures out that it is
void doSomething<int >(int) that should be called while
processing main.cpp, but it didn't see a reason to instantiate that
function while processing foo_templatestu ff.cpp.

Is there no other way but to define the whole function template
in the header file instead of the prototype only?
Yes, just put the whole function template in the header file. Unlike a
regular function definition, doing so will not cause link errors. Note
also that the function template is not inlined just because it is in
header file. The "inline" keyword would still have to be used if
inlining is intended.
Ok, there is simple but dirty solution by adding a function
void __dummy__() {
doSomething<int >(5);
}
to foo_templatestu ff.cpp.

It works but I don't like it. I don't want to write some dummy function
that touches all my operator templates for any specialization just to
make that *#!!$ compiler generate the accordant code.

There must be a better way ;-) ! Am I right?

bye, Micha


Depending on the compiler, it should be possible to explicitly
instantiate the function template. Of course the definition for the
template will be needed at the point of instantiation. Specializing the
template should also define it.

Moving the definitions into a header file will spare you these
headaches. It would match the way that everybody else, include the
standard library, does it. The compiler may end up compiling a little
more than it needs to. But the program after it is linked is the same
program whether you do have placed the templates in headers, or have
succeeded after much effort in putting them somewhere else.

Greg

Sep 27 '05 #7
Micha wrote:
As far as I got it, the idea is to have the compiler
generate the code for the specialized template classes
once only in the resulting TemplateInstanc es.o object
file.

Wouldn't implementing the whole template class in the
header file, force the compiler to instantiate the same
MyTemplateClass <MyType> class in every object file
generated from any .cpp file in which
MyTemplateClass <MyType> is used?


Yes and this is sometimes known as code bloat. But these days the linker
can eliminate duplicate template code so this is not a problem.

Put all template code in header files, it feels strange at first but it
is the right way to do it.

john
Sep 28 '05 #8
Thank you guys, it works and I can have my sleep ;-)

bye, Micha

Sep 28 '05 #9


Greg, you missed that he wrote #include "Vector.cpp ". Why some people
insist on putting template code in cpp files and then pulling all sorts
of tricks to compensate for this is beyond me.

john


John, my current approach when dealing with a LOT of template code is
to to put the implementation in a .hh file. Include the .hh file in
the .h file. How does this sound?

I'm unsure why it's necessary to make the function definitions inline
but I suspect I could peruse the standard to find out why.

I too place all my template code in a .h to make life easy. This
reminds me of a conversation I had with an individual who insists on
using void within his function arguments for member functions that take
no arguments. It drives me crazy and if I'm not mistaken they (see
below) don't mean the same thing in a C++ world but I didn't have proof
so I couldn't convice him.

bool test::some_func (void) <- the use of void here is not the same in
C++ correct?
{ return 1;}

Sep 29 '05 #10

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

Similar topics

6
1521
by: Roger Leigh | last post by:
I've written a fixed-precision class, "numeric". This stores the number of decimal places as a template parameter. I've overloaded all of the normal numerical operators (an example): template<unsigned short Dp> class numeric { public: // Round mode and precision are not assigned.
1
1335
by: Tom McCallum | last post by:
Hi, Can someone please tell me the correct syntax (if its possible of course) to specify an output stream operator for a templated class so that I dont need to write the same function for all the derived classes from the template. I have a sample of what it thought it might look like below. ==BEGIN CODE SNIPPET===
1
3974
by: Bo Xu | last post by:
Object of Combination By Bo Xu Introduction A combination of n things, taken s at a time, often referred as an s-combination out of n, is a way to select a subset of size s from a given set of size n. There are n!/(s!(n-s)!) ways to do this. Donald E. Knuth gives several methods (algorithms) to generate all the s-combinations in . In such procedure-oriented way, each s-combination is processed while it's being generated. In some
9
3423
by: Maciej | last post by:
Hi, I tried to build windl project from the book 'The Art of C++" in VS.NET 7 and it fails. I attached all required .lib files. I got the following error messages from the linker: windl error LNK2001: unresolved external symbol __malloc_dbg windl error LNK2019: unresolved external symbol __free_dbg referenced in function "void __cdecl operator delete(void *,struct std::_DebugHeapTag_t const &,char *,int)"...
4
1620
by: masood.iqbal | last post by:
Please help me with this doubt that I have regarding overloaded operators. Sometimes they are member functions and sometimes they are friends (e.g. see the code snippet from Stroustrup, Second Edition that I have posted to comp.sources.d). How do we decide which is more appropriate? Why are the overloaded "<<" and ">>" operators always friends? Also, what is an appropriate application for the overloaded function call operator?
2
1470
by: Niklas Norrthon | last post by:
I want to share a technique I recently have found to be useful to get around some obstacles that data protection can raise. Consider the following class: // foo.h #ifndef H_FOO #define H_FOO class Foo
25
3329
by: Ted | last post by:
I'm putting the posts that follow here (hopefully they will follow here!) because they were rejected in comp.lang.c++.moderated. It behooves anyone reading them to first read the the thread of the same subject in clc++m to get the more of the context. Ted
9
1697
by: Klaas Vantournhout | last post by:
Hi all, I have a question about friends functions of a template class. To make it simple, I would like to do something like this. Assume that I have a class foo with template T template<Tclass foo
4
1780
by: aaragon | last post by:
Hi everyone, I was unable to find out why my code is not compiling. I have a template class and I'm trying to write the operator<< for standard output. Does anyone know why this is not right? The code is as follows... // main class: template < class Individual,
0
8927
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
8764
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
9428
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
9289
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...
1
9210
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6026
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3242
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
3
2166
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.