Templates: How to use in projects

How should I emplement templated functions in projects?

I read that if a function is templated, it can't be represented by a prototype, so the emplementation has to be in a header, or wherever you want to use it.

So, what if I have a large project? Do I just have to copy/paste the emplementation into every .cpp file I need it in, or is there a nice and clean way to use header files for this?

Here's an example of a templated funstion I most likely may use in a lot of .cpp files:

1
2
3
4
5
6
7
8
9
10
11
/**Converts any class type to another.  Like from a string to an int,
or a float to a string, etc.. etc... */
template<class type1, class type2>
type2 conv(const type1& t1)
{
    stringstream ss;
    type2 t2 = type2();
    ss<< type1;
    ss>> type2;
    return type2;
}


I often use this kind of conversion in menus with extra options that, for practical use, must be represented by characters instead of numbers, where numbers are also used. Thus, conversion is necessary.

If I'm wrong, and it is possible to prototype this, please post the prototype syntax for me, thanks for the help!

EDIT1:
I made the type1 arg a const
Last edited on
I think you must put templates in header files so your compilation units are able to instantiate instances of the template.
Like this:
1
2
template<class type1, class type2>
type2 conv(type1& t1);

But there is probably not much need to do this. You can just define the function template in a header file.
Last edited on
so, what if I put the emplementation in the .cpp, and do this in the header:

1
2
template<class type1, class type2>
type2 conv(const type1&);
I believe that will give you some error messages, why don't you try it?
The implementation must be available when you use the template so that will not work. It's not an error if the template is defined in multiple translation units so defining it in the header is not a problem like with normal functions.
Build successful...

Oh, wait, nvm. Did not build.
Last edited on
> I read that if a function is templated, (...) the implementation has to be in a header, or wherever you want to use it.
> what if I have a large project?
> Do I just have to copy/paste the implementation into every .cpp file I need it in,
> or is there a nice and clean way to use header files for this?

I don't understand your issue.
¿You do know that you can `include' headers, right?


#include is equivalent to copy-paste.

> Did not build.
In general, there are error messages
Topic archived. No new replies allowed.