如何在(* this)上检查std :: is_base_of <>

问题描述 投票:0回答:2

对于某些任务,我没有没有宏就无法摆脱。现在,我想至少添加一些防止滥用的保护措施。

我想static_assert使用了MYMACRO()

  1. 在基类的子类中,...
  2. ...即,在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? -我希望上述解决方案可以简化本机体系结构下的单元测试,而无需使用native (POSIX) portQEMU / renodetarget board。 (不是全部,而是很多测试)

c++ gcc typetraits static-assert protothread
2个回答
0
投票

[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);
    }
};

编译器输出:

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);
                       ^~~

0
投票

typeid(*this)替换std::decay_t<decltype(*this)>

并且,要在编译时比较字符串,请使用std::string_view

static_assert(std::string_view(__func__) == "main", "Use MYMACRO() only in run() method.");
© www.soinside.com 2019 - 2024. All rights reserved.