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
259 views
in Technique[技术] by (71.8m points)

c++ - Nested Template Specialization

Having a brain fart... Is it possible to make something like this work?

template<int a> struct Foo
{
    template<int b> struct Bar;
};

template<int a> struct Foo<a>::Bar<1> //Trying to specialize Bar
{
};

I don't have to do this, but it will allow me to nicely hide some implementation details from namespace scope.

Suggestions appreciated!

P.S.: I forgot to mention that explicitly specializing for Bar within Foo's scope isn't supported by the language. AFAICS, anyway.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes, you can. But you'll need to change the call structure, but just a little bit.

Specifically, use the strategy pattern to restructure the implementation of the member function as a class (which IS allowed to be specialized).

This is permitted as long as the strategy class is not nested (and hence not dependent on the unspecialized template type).

e.g. (this probably isn't syntactically correct, but the idea should be clear)

template <class T>
class OuterThingThatIsNotSpecialized
{
  template <class U>
  void memberWeWantToSpecialize(const U& someObj_)
  {
    SpecializedStrategy<U>::doStuff(someObj_);
  }
};

template <class U>
struct SpecializedStrategy;

template <>
SpecializedStrategy<int>
{
  void doStuff(const int&)
  {
    // int impl
  } 
};

template <>
SpecializedStrategy<SomeOtherType>
{
  void doStuff(const SomeOtherType&)
  {
    // SOT impl
  } 
};

This is incredibly useful because calls to OuterThingThatIsNotSpecialized for types where no implementation exists will simply fail to compile.

PS. You can even use this strategy to partially specialize template functions, something that is an otherwise C++ impossibility.


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

...