[英]how to check std::is_base_of<> on (*this)
對於某些任務,如果沒有宏,我就無法逃脫。 現在我想至少添加一些防止誤用的保護。
我想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.");
typeid
在這里是錯誤的工具,因為它返回一個指向type_info
實例的引用,該實例不是*this
的類型,而僅包含有關類型的信息。
您可以使用decltype
:
#include <iostream>
#include <type_traits>
struct base {};
struct foo : base {
foo() {
static_assert(std::is_base_of<base,std::remove_reference<decltype(*this)>::type>::value);
}
};
struct foo_fail {
foo_fail() {
static_assert(std::is_base_of<base,std::remove_reference<decltype(*this)>::type>::value);
}
};
編譯器 output:
prog.cc: In constructor 'foo_fail::foo_fail()':
prog.cc:15:23: error: static assertion failed
static_assert(std::is_base_of<base,std::remove_reference<decltype(*this)>::type>::value);
^~~
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.