[转]c++使用宏检测类是否包含某个函数或者变量属性

对于特定的函数或者变量属性检测一个特定的参数类:

#include <iostream>
#include <boost/smart_ptr.hpp>

#include <type_traits>
using namespace boost;
using namespace std;

#define _CAT(A, B) A##B
#define STR(s) #s
#define CAT(A,B) _CAT(A,B)
#define CHECKER_PREFIX __has_member_function_
#define HAS_MEMBER_FUNC_CHECKER_NAME(FUNC) CAT(CHECKER_PREFIX, FUNC)

#define HAS_MEMBER_FUNC_CHECKER(FUNC) template <typename T> \
struct HAS_MEMBER_FUNC_CHECKER_NAME(FUNC){ \
template <typename C> static std::true_type test(decltype(&C::FUNC)); \
template <typename C> static std::false_type test(...); \
static constexpr bool value = std::is_same<decltype(test<T>(nullptr)),std::true_type>::value; \
};

#define HAS_MEMBER_FUNC(TYPE, FUNC) (HAS_MEMBER_FUNC_CHECKER_NAME(FUNC)<TYPE>::value)


class TestA{
public:
   int* foo(){

       int* a =new int(1);
       return a;

  }

   static int foo2(){
       return  1;
  }

   static const int foo3;
};

HAS_MEMBER_FUNC_CHECKER(foo);
HAS_MEMBER_FUNC_CHECKER(foo2);
HAS_MEMBER_FUNC_CHECKER(foo3);
int main() {

   static_assert(HAS_MEMBER_FUNC(TestA, foo));
   std::cout<<HAS_MEMBER_FUNC(TestA, foo) <<std::endl;

   return 0;
}

对于确定参数类型的泛型成员函数:

#include <iostream>
#include <boost/smart_ptr.hpp>

#include <type_traits>
using namespace boost;
using namespace std;

#define _CAT(A, B) A##B
#define STR(s) #s
#define CAT(A,B) _CAT(A,B)
// 对于固定个数的模版类,检测某一个属性或者函数是否存在
#define CHECKER_PREFIX2 _has_member_fcuntoin2_
#define HAS_MEMBER_FUNC_CHECK_NAME2_(FUNC) CAT(CHECKER_PREFIX2,FUNC)

#define HAS_MEMBER_FUNC_CEHCKER2(FUNC) template<typename T, typename R> \
   struct HAS_MEMBER_FUNC_CHECK_NAME2_(FUNC){ \
   template<typename C> static std::true_type test(decltype(&C::template FUNC<R>)); \
   template<typename C> static std::false_type test(...); \
   static constexpr bool value = std::is_same<decltype(test<T>(nullptr)),std::true_type>::value; \
}

// #define IF_HAS_MEMBER_FUNC2(FUNC,CLASS_,CLASS_F_T) (HAS_MEMBER_FUNC_CEHCK_NAME2_(FUNC)<CLASS_ ,CLASS_F_T>::value)


class TestA{
public:
   int* foo(){

       int* a =new int(1);
       return a;

  }

   static int foo2(){
       return  1;
  }

   template <typename T>
   static  int foo4(){
       return 1;
  }

   static const int foo3;
};


//含有固定类型的模版类
HAS_MEMBER_FUNC_CEHCKER2(foo4);

int main() {
   // 输出 1
   std::cout<< HAS_MEMBER_FUNC_CHECK_NAME2_(foo4)<TestA,char>::value << std::endl;
   // 输出 1
   std::cout<< HAS_MEMBER_FUNC_CHECK_NAME2_(foo4)<TestA,int>::value << std::endl;

   return 0;
}

See also:

https://blog.csdn.net/TH_NUM/article/details/90968219

https://harrychen.xyz/2019/06/04/cpp-17-mock-concept/

Monthly Archives

Pages

Powered by Movable Type 7.9.4

About this Entry

This page contains a single entry by Cnangel published on August 31, 2022 10:40 PM.

Linux磁盘分区问题 was the previous entry in this blog.

关于最近tensorflow去除内部abseil-cpp的一些link问题 is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.