不调用部分专用模板 class(用于容器 class 类型)

Partial specialized template class (for container class type) is not called

我仍在解决几个小时前发布的这个问题: [ 我试图实施这个解决方案。它编译但对象是使用 DerivedClass-Constructor 而不是部分专用模板创建的 class DerivedClass< Eigen::ArrayBase > 你知道我犯了(或一些)错误吗?

template <typename T> class BaseClass
{
protected:
  T mem;

public:
  BaseClass(T arg) : mem(arg){};
};

template <typename T> class DerivedClass : public BaseClass<T>
{
public:
  DerivedClass(T arg): BaseClass<T>(arg){};
};

template <typename T>
class DerivedClass<Eigen::ArrayBase<T> >
    : public DerivedClass<Eigen::ArrayBase<T> >
{
public: 
  DerivedClass(Eigen::ArrayBase<T> arg):BaseClass<Eigen::ArrayBase<T> >(arg){};
};

int main
{
...
  Eigen::Array3d arg = Array3d::Random(3);
  DerivedClass<Eigen::Array3d> o(arg);
....
}

如果 Eigen::Array3d 是某些 TEigen::ArrayBase<T> 的别名(通过 usingtypedef),您的代码应该有效。

但我认为 Eigen::Array3d 继承自 Eigen::ArrayBase<T>。所以不是``Eigen::ArrayBase`,所以不匹配部分特化,所以匹配主模板。

如果您想要拦截所有从 Eigen::ArrayBase 派生的 类 的特化,一个可能的解决方案是添加一个具有默认值的附加模板参数并仅激活它 T源自一些 Eigen::ArrayBase.

如下(注意:代码未测试)

constexpr std::false_type isArray (...);

template <typename T>
constexpr std::true_type isArray (Eigen::ArrayBase<T> const *);

template <typename T, typename = std::true_type>
class DerivedClass : public BaseClass<T>
 {
   public:
      DerivedClass(T arg): BaseClass<T>(arg){}; 
 };

template <typename T>
class DerivedClass<T, decltype(isArray(std::declval<T*>())>
   : public DerivedClass<T>
 {
   public: 
      DerivedClass (T arg) : BaseClass<T>(arg){};
 };
template<template<class...>class Z>
struct template_instance_test {
  static std::false_type test(...);
  template<class...Ts>
  static std::true_type test( Z<Ts...> const* );
  template<class X>
  using tester = decltype(test( std::declval<X*>() ) );
};
template<template<class...>class Z, class T>
using is_derived_from_template = typename template_instance_test<Z>::template tester<T>;

我们现在可以询问某物是否是特定模板的实例,或派生自特定模板的实例。

template<class X>
struct Base {};
template<class X>
struct Derived:Base<X> {};

template<class T>
struct Storage {
  T data;
};
template<class T, class=void>
struct Instance:Storage<T> {
  enum {is_special = false};
};
template<class T>
struct Instance<T, std::enable_if_t< is_derived_from_template<Base, T>{} > >:
  Storage<T> {
  enum { is_special = true };
};

int main() {
    Instance<int> i; (void)i;
    static_assert(!Instance<int>::is_special);
    Instance<Derived<int>> j; (void)j;
    static_assert(is_derived_from_template<Base, Base<int>>{});
    static_assert(is_derived_from_template<Base, Derived<int>>{});
    static_assert(Instance<Derived<int>>::is_special);
}

我们完成了。 Live example.