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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With