Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template methods and template classes C++

Can class member functions be template functions, or must they be static class functions. Basically can the class and the function be technically instantiated separately on demand?

What are the limitations of using a template function as a member of a template class? Can both be done at the same time at all, or is it either or?

like image 842
rubixibuc Avatar asked Oct 08 '11 05:10

rubixibuc


People also ask

What is the difference between class template and template class?

A class template is a template that is used to generate classes whereas a template class is a class that is produced by a template.

What is template class and template function?

Function templates. Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.

What is a class template in C?

A class template provides a specification for generating classes based on parameters. Class templates are generally used to implement containers. A class template is instantiated by passing a given set of types to it as template arguments.

Is class template and function template the same?

The difference is, that the compiler does type checking before template expansion. The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of the same function/class. Function Templates We write a generic function that can be used for different data types.


2 Answers

You can have template member functions of template classes, like this:

template <typename T>
class Foo {
public:
    template <typename U>
    void bar(const T& t, const U& u);
};

template <typename T>
template <typename U>
void Foo<T>::bar(const T& t, const U& u) {
    // ...
}
like image 179
Jonathan Callen Avatar answered Oct 09 '22 12:10

Jonathan Callen


Class methods can be template. The only limitation is they can't be virtual.

EDIT :

To be more complete, constructor can also be template

class X
{

    template<typename T>
    X( T t )
    {

    }

};

But of course, there should only be one non-template destructor

like image 37
crazyjul Avatar answered Oct 09 '22 14:10

crazyjul