Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check at compile time class constructor signature

Tags:

c++

boost

Is there a way to check at compile time if some class has constructor with certain arguments ? ?

For example:

class foo {
    foo(std::string &s) {
    }
};

I want to check at compile time that constructor with std::string& always defined. Maybe boost provides such functionality ?

like image 651
Konstantin Avatar asked Jun 04 '09 09:06

Konstantin


1 Answers

The common way to check if a specific function exists is to take its address and assign it to a dummy variable. This is a lot more precise than the tests mentioned so far, because this verifies the exact function signature. And the question was specifically about string& in the signature, so non-const and thus presumably modifying the string.

However, in this case you cannot use the take-the-address-and-assign-it trick: constructors don't have addresses. So, how do you check the signature then? Simply: Befriend it in a dummy class.

template<typename T>
class checkSignature_StringRef {
    friend T::T(string&);
};

This too is a very specific check: it will not even match similar constructors like foo::foo(std::string &s, int dummy = 0).

like image 174
MSalters Avatar answered Sep 23 '22 03:09

MSalters