开发者

template specialization with multiple template parameters

Say I have this:

template<typename T, int X>
class foo 
{
public:
  voi开发者_Go百科d 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.


No. That is not allowed. A class member function must be fully specialized. For example, it should be,

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


You can partially specialize the whole class. In this case you can give different implementations to the set function for every specialization of the class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜