boost/c++11 变量类型打印、相等判断以及成员函数指针相关

boost 中有一个模板函数 type_id_with_cvr 可以将变量类型的描述信息打印出来。

std::is_same 用于判断两个类型是否一致,强规则判断模式,例如 const int != int;
std::decay 用于判断两个类型是否一致,弱规则判断模式,例如 const int == int;
如下代码例子中 void (*)(int const&) 表示变量类型,void (*func_pointer)(int const&) 表示定义了一个指针变量func_pointer。
普通函数指针只能指向类的静态成员函数,成员函数指针可以指向任意类的成员函数。
类的成员函数是无法直接调用的,必须要使用对象或者对象指针调用(这样函数才能通过对象获取到this指针)。::* .* ->* 都是编译器提供的新的操作符 支持成员函数指针的操作。
#include <boost/type_index.hpp>
using namespace std;
using boost::typeindex::type_id_with_cvr;

template <typename T>
void printType(string s)
{
    cout << s << " = " << type_id_with_cvr<T>().pretty_name() << endl;
}

template <typename T, typename U>
struct decay_equiv :
    std::is_same<typename std::decay<T>::type, U>::type
{};

class Test {
    public:
        Test() {};
        ~Test() {};
        void func(const int &i) {
            std::cout << "This is Test::func "<<std::endl;
        }
        
        static void printTest() {
            std::cout << "printTest "<<std::endl;
        }
};

//成员函数指针
typedef void (Test::*p_test_func)(int const&);

void test_func(const int &i)
{
    std::cout << "This is test_func "<<std::endl;
}

int main (int argc, char *argv[]) {

    //decltype(&Test::func)* my_test;
    printType<decltype(&Test::func)*>("TEST ");
    //TEST  = void (Test::**)(int const&)
    
    printType<decltype(&test_func)>("test_func ");
    //test_func  = void (*)(int const&)
    decltype(&test_func) f_pointer = test_func;
    f_pointer(2);
    
    //定义成员函数指针变量
    p_test_func my_func_test = &Test::func;
    
    Test t;
    Test *tt = new Test;
    //成员函数调用方式
    (t.*my_func_test)(2);
    (tt->*my_func_test)(2);
    
    //静态成员函数指针
    void (*s_fptr)() = &Test::printTest;
    s_fptr();
    void (Test::*fptr)(int const&) = &Test::func;   
    (t.*fptr)();
    
    std::cout<< " result = "<< std::is_same<decltype(&Test::func)*, void (Test::**)(int)>::value << std::endl;  //true
    std::cout<< " result = "<< decay_equiv<decltype(&Test::func)*, void (Test::**)(int)>::value << std::endl;    //true
    return 0;
}
原文地址:https://www.cnblogs.com/rayfloyd/p/14307590.html