Markus
Markus

Reputation: 373

c++ template member function with partial spezialisation outside class

this code use a template member that work different for std::vector and other types. So far it works fine. But what is the correct syntax to define the get methode for std::vector outside the class ? i am aware about using traits and other helpers to make this working but i would like this simple solutions if there is an valid syntax.

#include <iostream>
#include <vector>

using namespace std;

struct s
{
  template < class X > void get (X x)
  { 
      cout << "inner\n";
  };
  
  template <class X> void get(std::vector<X> vec)
  {
      cout << "inline any vector\n";
  }

};

int main ()
{
  std::vector < int >vec;
  std::vector< double> dvec;
  s x;
  x.get (1);
  x.get (vec);
  x.get(dvec);
  return 0;
}

this seems not to work

template <class X> void s::get(std::vector<X> v) 
{
}

Upvotes: 1

Views: 117

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117168

what is the correct syntax to define the get methode for std::vector outside the class ?

That would be to just declare it in the class template and then go ahead and define it outside:

struct s {
    template < class X > 
    void get (X x) { 
        cout << "inner\n";
    }

    template <class X>            // declaration
    void get(std::vector<X> v);
};

template <class X>                // definition
void s::get(std::vector<X> v) {}

Upvotes: 2

Related Questions