Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template specialization with multiple template parameters

Say I have this:

template<typename T, int X>
class foo 
{
public:
  void set(const T &t);
};

template<typename T, int X>
void foo::set<T, X>(const T &t)
{
  int s = X;
  // ...etc
}

Could I specialize the function type 'T' but leave 'X' as a template parameter?

class bar;

template<int X>
void foo::set<bar, X>(const bar &t)
{
  int s = X;
  // ...etc
}

Is this possible?

like image 208
MarkP Avatar asked Oct 04 '11 04:10

MarkP


2 Answers

This is surprisingly easy once you get the hang of it

template<typename T, int X>
class foo 
{
private:
  template<typename, int> class params { };

public:
  void set(const T &t) {
    set(t, params<T, X>());
  }

private:
  template<typename T1, int X1>
  void set(const T1 &t, params<T1, X1>) {
     // ...
  }

  template<int X1>
  void set(const bar &t, params<bar, X1>) {
    // ...
  }
};

This is necessary because if you explicitly specialize a single member, you must provide all template arguments. You cannot leave some off.

like image 160
Johannes Schaub - litb Avatar answered Nov 09 '22 10:11

Johannes Schaub - litb


You could consider rewriting your code to make the member function a separate template:

template <int X> class foo
{
  template <typename T> void set(const T &);
  // ...
};

Then you can provide explicit specializations for the template foo<X>::set.

like image 39
Kerrek SB Avatar answered Nov 09 '22 08:11

Kerrek SB