How to call a generic function of a template in a specialization version

You are having a problem with how to invoke the generic version of the template in the specialization version.

Here is a sample code. But "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; } 
+6
source share
3 answers

When you create a specialization for a template (without a difference class of a function), you tell the compiler to generate one, not the general one . So, if you have a specialization, you do not have a generic version for this specialization, and you cannot name it because it does not exist .

+6
source

Well, in addition, I think it works to specify the function of a template in some situations.

 #include <iostream> #include <vector> using namespace std; class Base { public: virtual int test() {return 0;} }; class Derived : public Base { public: virtual int test() {return 1;} }; template<class T> void TestOutput(T* a) { cout << a->test() << endl; } template<> void TestOutput(Derived* a) { cout << "something else" << endl; TestOutput<Base>(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 the TestOutput function for Base to call the generic one.

0
source

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); } 
0
source

Source: https://habr.com/ru/post/892645/


All Articles