I’m making a cross-platform library implementing several basic primitives on several platforms. To verify that every implementation of a primitive (i.e. class) provides core members required on all platforms I use the following construct:
template<typename _Ty> int _MethodVerifyHelper(_Ty);
#define ENSURE_MEMBER_DECL(className, methodName, returnType, ...) typedef char __PROTOTYPE_VERIFIER__[sizeof(_MethodVerifyHelper<returnType (className::*)(__VA_ARGS__)>(&className::methodName))]
Then I write something like this:
ENSURE_MEMBER_DECL(Event, TryWait, bool, unsigned);
So if the Event class has no bool TryWait(unsigned) method, we’ll get a compilation error here.
The question is: is there a similar syntax in C++ to declare pointers to constructors? I want to have a statement that causes a compile-time error if a class does not provide a constructor with given argument types.
There’s no way you can take the address of a constructor, but you can
easily get a compile time error if an object can’t be constructed with a
given set of arguments:
The essential part is, of course, the
sizeofexpression, whichcontains a construction of the object which will never be evaluated, but
which must be legal. It’s wrapped in a
typedefto ensure that itwon’t generate any code, ever.