调用模板参数的构造函数 [英] Call constructor of template parameter

查看:189
本文介绍了调用模板参数的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出了模板化工厂方法,我想根据template参数提供的构造函数来调用不同的构造函数:

Given a templated factory method, I would like to call different constructors based on the constructors the template parameter provides:

template<typename T>
T* Factory::create()
{
  if (hasOnlyDefaultConstructor<T>())
    return new T();
  else
    return new T(this);
}

两个问题:

  • 如果T没有构造函数T(Factory *),则存在编译问题.
  • 如何编写hasOnlyDefaultConstructor()?

一般来说,我想要以下内容:

In general I would like the following:

template<typename T>
T* Factory::create()
{
  if (hasDefaultConstructor<T>())
    return new T();
  else if (hasUnaryConstructor<T>())
    return new T(create());
  else if (hasBinaryConstructor<T>())
    return new T(create(), create());
  else ....
}

有没有一种方法可以在C ++中实现?如果编译器有多个构造函数可供选择,我会理解这些问题,但是,我们只传递类型T,而类型T恰好具有一个公共构造函数.

Is there a way to achieve this in C++? I understand the problems if there are multiple constructors for the compiler to choose, but let's say that we only pass types T which have exactly one public constructor.

class A 
{
  A(B* b);
}

class B 
{
  B(C* c, D* d);
}  

A* a = Factory::create<A>(); // same as A* a = new A(new B());
B* b = Factory::create<B>(); // same as B* b = new B(new C(), new D());

是否不可能编写一个可以实例化B和A的通用函数create()?

Shouldn't it be possible to write a generic function create(), which could instantiate both B and A?

推荐答案

您可能想要这样:

struct X
{
  enum {TYPE = 0;}// has default constructor
  X() {}
};


struct A
{
  enum {TYPE = 1;}
  typedef B P;
  A(P* p) {}
};

struct B
{
  enum {TYPE = 2;}
  typedef C P1;
  typedef D P2;
  B(P1* p1, P2* p2) {}
};

template<T, type> //type default = 0
struct FactoryDetail<T>
{
  static T* create(){return new T(); } 
};

template<T>
struct FactoryDetail<T, 1>
{
  static T* create(){return new T(new typename T::P()); } 
};

template<T>
struct FactoryDetail<T, 2>
{
  static T* create(){return new T(new typename T::P1(), new typename T::P2()); } 
};

//final Factory
template<T>
struct Factory
{
  static T* create(){return FactoryDetail<T, T::TYPE>::create(); } 
};

我现在没有开发环境,上面的代码描述了基本思想.

I don't have dev environment now, the above codes describing the basic idea.

这篇关于调用模板参数的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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