I have read that C++11 has sufficient static checking (compile time) so as to implement a big part of what should have been Concepts checking of C++11(removed). (I’ve read this in the comments of a recent question about Concepts removed… – that question was fastly closed as not constructive).
The C++03 code below only check the presence of a member function in a class (on which my template class wants to work). Here are 4 member functions that are searched for, and I always use the same pattern:
- a typedef to define a typedef of the prototype of the function
- a call to static_cast that breaks compilation if ever the typename TExtension doesn’t define such a member function, or if it has different prototype
Here is the code:
template <typename TExtension>
class
{
...
void checkTemplateConcept()
{
typedef unsigned long (TExtension::*memberfunctionRequestedId)();
static_cast<memberfunctionRequestedId>(&TExtension::getRequestId);
typedef eDirection (TExtension::*memberfunctionDirection)();
static_cast<memberfunctionDirection>(&TExtension::getDirection);
typedef eDriveWay (TExtension::*memberfunctionDriveWay)();
static_cast<memberfunctionDriveWay>(&TExtension::getDriveWay);
typedef unsigned long (TExtension::*memberfunctionCycleId)();
static_cast<memberfunctionCycleId>(&TExtension::getCycleId);
}
}
This was in some part of my code, but it was completely based on C++03. I would rewrite it gladly, with those new C++11 features… what should be used here instead ?
With C++11, you could make the compiler to print the good error messages with
static_assertas:Now if the type of member function doesn’t match, the compiler will print this helpful message:
You could make it more descriptive if you want to. 🙂