Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How the has_trivial_default_constructor works?

Can somebody explain me how has_trivial_default_constructor works? I tried to find it in a boost implementation but unfortunately there are too many macros and I just got lost...

How somebody can detect the trivial_default_constructor in C++ using templates?

I need an example in C++ 03 not 11.

#include <boost/type_traits.hpp>
#include <boost/static_assert.hpp>

  struct A{
    A(){}
    int a;
    //std::vector< int > b;
  };

int main(int argc, char* argv[])
{
  struct B{
    std::vector< int > b;
  };


  bool result =  boost::has_trivial_default_constructor<A>::value;

  //std::forward(&test);
  return 0;
}
like image 874
AlexTheo Avatar asked Mar 02 '14 22:03

AlexTheo


1 Answers

Actually, it's impossible (in pure C++).

Detecting whether a type has a default constructor is possible with SFINAE because it only involves the interface, but detecting whether it's trivial involves the implementation.

Therefore, a compiler must provide a specific intrinsic for this. You can find a list of intrinsics here, note that some are provided because they require a compiler intervention and others may be provided just to have a uniform set or streamline the Standard Library implementation.

The particular intrinsic you are looking for is either __has_trivial_constructor which is also supported by gcc and MSVC according to the comments or __is_trivially_constructible (Clang's specific). I must admit being slightly unsure of the former (what if the type has several constructors ?), the latter can be used as:

template <typename T>
struct has_trivial_default_constructor {
    static bool const value = __is_trivially_constructible(T);
};
like image 116
Matthieu M. Avatar answered Oct 18 '22 19:10

Matthieu M.