嵌套模板专业化 [英] Nested Template Specialization

查看:135
本文介绍了嵌套模板专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个大脑放屁...可以做这样的工作吗?

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

template< int a> struct Foo :: Bar <1> //尝试专门化Bar
{
};

我不是这样做,



建议赞赏!



PS:我忘了提及明确专用于Foo的范围内的Bar不被语言支持。

解决方案

是的,你可以。



具体来说,使用策略模式将成员函数的实现重构为一个类



这是允许的,只要策略类不是嵌套的(因此不依赖于非特定的模板类型)。



例如(这可能在语法上不正确,但是想法应该很清楚)

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

template< class U>
struct SpecializedStrategy;

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

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

这是非常有用的,因为对于没有实现的类型调用OuterThingThatIsNotSpecialized将无法编译。 / p>

PS。你甚至可以使用这个策略来部分专门化模板函数,这是C ++不可能的东西。


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.

解决方案

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.

这篇关于嵌套模板专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆