Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

c++ - Partially specializing member-function implementations

I'm currently refactoring some code the explicitly specializes a member function of a class template with two template parameters.

template <class S, class T>
class Foo
{
  void bar();
};

template <class S, class T>
void Foo<S, T>::bar()
{ /* Generic stuff */ }

template <>
void Foo<SomeType, SomeType>::bar()
{ /* Some special function */ }

Now I added some more template parameters, so the class now looks like this:

template <class S, class EXTRA0, class T, class EXTRA1>
class Foo
{
  void bar();
};

These two extra parameters just add typedefs to my class, so the run-time functionality doesn't really change. Is there any way I can keep the (now partially) specialized implementation of bar? I can't seem to figure out the syntax for that and I have a hunch that it might not be possible.

Edit: I'm looking for something like:

template <class EXTRA0, class EXTRA1>
void foo<SomeType, EXTRA0, Sometype, EXTRA1>::bar()
{
   /* specialized implementation */
}

which does not seem to compile..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are correct, it is not possible.

What you can do is create a helper member class template inside the new Foo, and place the specialized function inside it as a non-template member function. Specialize the helper class instead of the function.

Another alternative is to turn the specialization into a non-template overload.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...