Home > Back-end >  Enable constructor iff two member functions are present in the passed template type
Enable constructor iff two member functions are present in the passed template type

Time:07-17

With this code:

struct MyStructure {
  MyStructure(char* d, int size) {}

  template <typename T>
  MyStructure(T&& rhs) : MyStructure(rhs.data(), rhs.size()) {}
};

How can I only enable the second constructor to be present if the data and size functions are present in whatever object is passed in?

CodePudding user response:

Here is what Sam Varshavchik meant, which should work with C 11:

struct MyStructure {
  MyStructure(char* d, int size) {}

  template <typename T, 
     decltype(static_cast<char*>(std::declval<T &&>().data())) = nullptr,
     decltype(static_cast<int>(std::declval<T &&>().size())) = 0
     >
  MyStructure(T&& rhs) : MyStructure(rhs.data(), rhs.size()) {}
};
  • Related