How can I have an optional default constructor?

This class:

template <class T>
struct A {
  A() : t(T()) {
  } 

  A(const T& t_) : t(t_) {
  }

  T t;
};

will not compile unless T has a default constructor. It:

template <class T>
struct A {
  A(const T& t_) : t(t_) {
  }

  T t;
};

will not have a default constructor, even if T has a default constructor.

I want to have both - if there is no T (), I do not want A ().

I know what SFINAE needs to use. And that Boost.traits and Boost.enable_if can help, but I can't get it to work. Can someone give me an example of this simple case?

+3
source share
2 answers

Member functions of class templates are only created when called. If you never call A::A(), then the calling code T::T()should not compile in this code:

template <class T>
struct A {
  A() : t(T()) {
  }
  // ...
};

? , ?

, A , , , - T A::A() :

template< typename T >
struct default_a_ traits {
  static T default_construct()
  {
    return T();
  }
};

template <class T, class Traits = default_a_traits<T> >
struct A {
  A() : t(Traits::default_construct()) {
  }
  // ...
};

, , , T - :

struct my_special_traits_for_b {
  static T default_construct()
  {
    return read_b_from_db();
  }
};

typedef A<B, special_traits_for_b> AB;
+1

:

template <class T>
struct A {
  A(const T& t_ = T()) : t(t_) {
  }

  T t;
};
0

Source: https://habr.com/ru/post/1721451/


All Articles