【问题标题】:C++ template specialization from child type来自子类型的 C++ 模板特化
【发布时间】:2014-01-11 17:05:59
【问题描述】:

我有一个类层次结构,例如:

          A<int, int>
          / \
B<int,int>   C<int,int>

还有一个类Foo&lt;int, int&gt;,其中包含这些类型的成员列表。它们不能组合成一个 As 列表,因为我需要单独操作它们。无论如何(仅在 C++98 中)添加一个可以将它们正确插入到正确容器中的方法,例如:

template<int X, int Y>
class Foo
{
  std::vector< shared_ptr<B<int, int> > > mBs;
  std::vector< shared_ptr<C<int, int> > > mCs;

  template<template <int, int> class T>
  add_element
  {
     mBs.insert(shared_ptr<B<X, Y> >(new B<x, Y>()); if its a B
     mCs.insert(shared_ptr<C<X, Y> >(new C<x, Y>()); if its a C
  }
};

并在客户端代码中执行此操作:

Foo bar;
bar.add_element<TypeDerivedFromB>();
bar.add_element<TypeDerivedFromC>();

我可以有两个不同的函数,但是这会让界面有点讨厌。谢谢

【问题讨论】:

  • SFINAE on std::is_base_of.
  • 谢谢,但是很遗憾不能使用 C++11。
  • Boost.TypeTraits is_base_of 然后。需要帮助吗?
  • 只写两个重载,每个类型一个。
  • 这引出了一个问题:以及从两者派生的类是什么

标签: c++


【解决方案1】:

以下可能会有所帮助。 它使用 SFINAE:

template<int X, int Y> class B{};
template<int X, int Y> class C{};

template<int X, int Y>
class Foo
{
  std::vector< std::shared_ptr<B<X, Y> > > mBs;
  std::vector< std::shared_ptr<C<X, Y> > > mCs;

public:
  template<template <int, int> class T>
  typename std::enable_if<std::is_same<T<X, Y>, B<X, Y> >::value>::type
  add_element()
  {
    mBs.push_back(std::shared_ptr<B<X, Y> >(new B<X, Y>));
  }

  template<template <int, int> class T>
  typename std::enable_if<std::is_same<T<X, Y>, C<X, Y> >::value>::type
  add_element()
  {
    mCs.push_back(std::shared_ptr<C<X, Y> >(new C<X, Y>));
  }

};

不确定它是否比 2 个不同名称的方法更好...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多