c++ - 如何检查 (*this) 上的 std::is_base_of<>
问题描述
对于某些任务,如果没有宏,我就无法逃脱。现在我想至少添加一些防止误用的保护。
我想static_assert
使用 MYMACRO()
- 在基类的子类中,...
- ...即,在
run()
方法中
一种天真的方法失败了:
static_assert(std::is_base_of<Base, typeid(*this)>::value, "Use MYMACRO() only in subclass of Base.");
// =============
// SubOne would work, but not typeid(*this)
//
static_assert(__func__ == "run", "Use MYMACRO() only in run() method.");
// ========
// not a constexpr?
//
重现:
#ifndef __GNUG__
#error "Needs GCC C++"
#endif
#define MYMACRO() \
{\
do { \
/*> > > want static_assert'ions here < < <*/\
/*here comes stuff I coudn't put into an [inline] function,*/ \
/*because it contains GCC Labels-as-Values and */ \
/*conditional return;*/ \
} while(false);\
}
class Base {
public:
virtual int run() = 0;
};
class SubOne : Base {
public:
int run() override {
// ...
MYMACRO();
// ...
};
};
class SubTwo : Base {
public:
int run() override {
// ...
MYMACRO();
// ...
};
};
int main(void)
{
SubOne sub1;
SubTwo sub2;
//a little embedded app
while (true) {
sub1.run();
sub2.run();
}
}
预测可能的问题:
它有什么用?- http://dunkels.com/adam/dunkels06protothreads.pdf
标签作为值: - https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html为什么不使用上下文切换
“正确” RTOS ?- 我希望上述解决方案能够简化本机架构下的单元测试,避开对本机 (POSIX) 端口或QEMU / renode或目标板的需求。(不是针对所有人,而是针对许多测试)
解决方案
替换typeid(*this)
为std::decay_t<decltype(*this)>
。
并且,要在编译时比较字符串,请使用std::string_view
:
static_assert(std::string_view(__func__) == "main", "Use MYMACRO() only in run() method.");
推荐阅读
- sapui5 - 如何使用 ui5-cli 启动我的 UI5 项目,其 URL 为“localhost:8080/#”而没有“index.html”?
- python - 带有 scikit-learn 的 Spyder 中的“某些库已导入但未使用”警告
- github - Travis CI 未在 GitHub 组织存储库更改时触发
- three.js - 如何在threejs中从俯仰,滚动和航向执行3d模型的完全旋转?
- c# - 如何使用身份 2.2 并且不在 ApplicationUserManager 上使用 ILookupNormalizer
- java - Selenium 自动化 - 如何从此列表中选择下拉菜单项而不会出现异常错误?
- java - 我无法从测试包到主包进行 ComponentScan
- datetime - W3C 承认的 UTC 日期时间格式是否与 ISO 8601 相同?
- java - BCrypt 使用 Java 和 PHP,发送加密的密码并对其进行解码
- javascript - 如何从存储 javascript 对象的 mysql 列中取回有效的 JSON