Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...