c++ - 不调用部分专用模板类(用于容器类类型)

标签 c++ templates partial specialization

我仍在处理几个小时前发布的这个问题: [ How to overload/specialize template class function to handle arithmetic types and a container-class 我试图实现这个解决方案。它编译但对象是使用 DerivedClass-Constructor 而不是部分专用模板类 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);
....
}

最佳答案

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 .

关于c++ - 不调用部分专用模板类(用于容器类类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53562849/

相关文章:

c++ - 在模板特化中映射枚举

c++ - 在模板上使用 ()-运算符

javascript - Node 部分搜索

jquery - 是否可以在 render partial 中传递参数?

text - UWP 中 'TextBlock' 的绑定(bind)部分

C++动态加载dll错误

c++ - 这个 getter 返回的是构造函数给出的引用还是类内部对象的引用? C++

c++ - 如何从另一个文件 : C++ 访问类的公共(public)枚举

c++ - 如何安全地将整数类型转换为作用域枚举

c++ - 传递具有依赖嵌套参数类型的模板模板参数时出错