3

This class:

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

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

  T t;
};

won't compile if T doesn't have default constructor. This one:

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

  T t;
};

won't have default constructor even if T has default constructor.

I want to have both - If there's no T() I want no A().

I know that SFINAE have to be used. And that Boost.traits and Boost.enable_if can help, but I can't get it to work. Can Someone give me an example to this simple case?

4

2 回答 2

1

类模板的成员函数只有在您调用它们时才会被实例化。如果您从不调用A::A(),则T::T()不应在此代码中编译调用代码:

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

你有这个问题吗?如果是这样,您使用的是哪个编译器?

也就是说,如果代码 usingA调用其默认构造函数,那么我看到的唯一出路是将 inside 的创建移动TA::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;
于 2009-11-03T07:34:55.430 回答
0

尝试这个:

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

  T t;
};
于 2009-10-30T21:35:24.727 回答