我读到 C++11 有足够的静态检查(编译时),以便实现 C++11 的大部分内容(已删除)。 (我在最近关于已删除概念的问题的评论中读到过此内容... - 该问题因不具有建设性而很快被关闭)。
下面的 C++03 代码仅检查类中是否存在成员函数(我的模板类要在该类上工作)。这里有 4 个搜索的成员函数,我总是使用相同的模式:
代码如下:
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);
}
}
这是我代码的一部分,但它完全基于 C++03。我很乐意用那些新的 C++11 特性重写它……这里应该使用什么?
最佳答案
使用 C++11,您可以让编译器使用 static_assert 打印正确的错误消息,如下所示:
typedef unsigned long (TExtension::*required_type)();
typedef decltype(&TExtension::getRequestId) actual_type;
static_assert(std::is_same<required_type, actual_type>::value,
"The type of getRequestId must be unsigned long (C::*)()");
现在,如果成员函数的类型不匹配,编译器将打印这条有用的消息:
"The type of getRequestId must be unsigned long (C::*)()"
如果你愿意,你可以让它更具描述性。 :-)
关于c++ - 成员函数检查 : Implement compilation-time checkings with C++11 features,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14403941/