Sunday, August 19, 2018

How to call generic template function in a specialization version

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 
#include 

using namespace std;

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

int main()
{
        vector v;
        v.push_back(10);
        v.push_back(1);
        return 0;
}

Solved

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.


Well, to complement, I think it works for template function specification in some situations.

#include 
#include 

using namespace std;

class Base
{
public:
    virtual int test() {return 0;}
};

class Derived : public Base
{
public:
    virtual int test() {return 1;}
};

template
void TestOutput(T* a)
{
    cout << a->test() << endl;
}

template<>
void TestOutput(Derived* a)
{
    cout << "something else" << endl;
    TestOutput(a);
}

int main()
{
    Derived d;
    TestOutput(&d);
}

I compiled it with visual studio 2013 and the output is:

something else 1

Although I don't think you can always find a TestOutput function of Base to call the generic one.


You can simply extract the code into another template function:

    template
    void baseF(T t) { ... }

    template
    void F(T t) { baseF(t); }

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

No comments:

Post a Comment