简体   繁体   English

没有默认构造函数的模板的构造函数

[英]Constructors for templates that do not have default constructors

I have a template class that currently has a constructor that takes no arguments. 我有一个模板类,当前有一个不带参数的构造函数。 The issue is that in some cases the class that is being used in the template does not have an empty constructor which gives compile errors. 问题在于,在某些情况下,模板中使用的类没有空的构造函数,该构造函数会产生编译错误。

template <typename T>
class A
{
     public:
     T Thing;
     int number;
     A():number(5) {}
 };


  class B
  {
       public:
       int a;
       B(int _a):a(_a) {}
  }

  A<int> a1; // This is fine
  A<B> a2; // This is not fine since B has no default constructor

I've thought of possibly using adding a second constructor which takes a ref to T, and then using enable_if to remove the parameterless constructor if T does not have a default constructor, but I'm not sure if that would work. 我曾考虑过可能要添加一个第二个构造函数,该构造函数将对T的引用传递给T,然后如果T没有默认构造函数,则使用enable_if删除无参数构造函数,但是我不确定这是否可行。 Are there other options? 还有其他选择吗?

Note that I do not want to add a default constructor to class B because I don't want to leave an instance of B in an unknown state. 请注意,我不想向类B添加默认构造函数,因为我不想让B的实例处于未知状态。

Spoke to some people and did more research and found the solution. 向一些人发表讲话,进行了更多研究并找到了解决方案。 Making the default constructor templated by a constexpr static member. 使默认构造函数以constexpr静态成员为模板。 Here it is: 这里是:

template <typename T>
class A
{
public:
     T Thing;
     int number;
     static constexpr bool HasDefaultConstructors = std::is_default_constructible<T>;

     // This removes the default constructor if T does not have one
     template<bool HDC = HasDefaultConstructors, typename std::enable_if<HDC, int>::type = 0>
     A():number(5) {}

     A(const Thing &t):T(t) {}
 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM