Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call generic template function in a specialization version

Tags:

c++

Have a problem about how to call the generic template version in a specialization version.

Here is the sample code. But the "vector::push_back(a)" calls itself recursively.

#include <iostream>
#include <vector>

using namespace std;

namespace std
{
        template<>
        void vector<int>::push_back(const int &a)
        {
                cout << "in push_back: " << a << endl;
                vector::push_back(a);               // Want to call generic version
        }
}

int main()
{
        vector<int> v;
        v.push_back(10);
        v.push_back(1);
        return 0;
}
like image 760
user842071 Avatar asked Jul 13 '11 06:07

user842071


People also ask

When we specialize a function template it is called?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

How do you call a function template?

A function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.

Can you partially specialize a C++ function template?

You can choose to specialize only some of the parameters of a class template. This is known as partial specialization. Note that function templates cannot be partially specialized; use overloading to achieve the same effect.

Are template specializations inline?

An explicit specialization of a function template is inline only if it is declared with the inline specifier (or defined as deleted), it doesn't matter if the primary template is inline.


2 Answers

When you create specialization for some template (no difference class of function), you tell to compiler to generate that one instead of general. So in fact if you have specialization you have no general version for that specialization and you can't call it, because it doesn't exists.

like image 114
Mihran Hovsepyan Avatar answered Nov 25 '22 07:11

Mihran Hovsepyan


You can simply extract the code into another template function:

    template<typename T>
    void baseF(T t) { ... }

    template<typename T>
    void F(T t) { baseF<T>(t); }

    template<>
    void F<int>(int t) { baseF<int>(t); }
like image 29
etham Avatar answered Nov 25 '22 08:11

etham