从静态和模板化成员函数中提取类

时间:2017-02-03 04:38:17

标签: c++ c++11 templates template-meta-programming member-function-pointers

请考虑以下代码:

#include <iostream>
#include <type_traits>
#include <typeinfo>

struct object
{
    void f0(int i) {std::cout<<i<<std::endl;}
    void f1(int i) const {std::cout<<i<<std::endl;}
    void f2(int i) volatile {std::cout<<i<<std::endl;}
    void f3(int i) const volatile {std::cout<<i<<std::endl;}
    constexpr int f4(int i) const noexcept {return i;}
    static void f5(int i) {std::cout<<i<<std::endl;}
    template <class T> void f(T i) {std::cout<<i<<std::endl;}
};

template <class T, class C>
void print_class_containing(T C::* ptr)
{
    std::cout<<"typeid(C).name() = "<<typeid(C).name()<<std::endl;
}

int main(int argc, char* argv[])
{
    std::cout<<"typeid(object).name() = "<<typeid(object).name()<<std::endl;
    print_class_containing(&object::f0);
    print_class_containing(&object::f1);
    print_class_containing(&object::f2);
    print_class_containing(&object::f3);
    print_class_containing(&object::f4);
    //print_class_containing(&object::f5); -> Not compiling
    //print_class_containing(&object::f); -> Not compiling
    return 0;
}

如何编写函数以及如何调用它来打印“包含”指向静态成员函数(f5)的指针的类,以及指向模板化成员函数的指针(f )?

目前,编译器返回:

static_member.cpp:30:5: error: no matching function for call to 'print_class_containing'
    print_class_containing(&object::f5); // -> Not compiling
    ^~~~~~~~~~~~~~~~~~~~~~
static_member.cpp:17:6: note: candidate template ignored: could not match 'T C::*' against 'void (*)(int)'
void print_class_containing(T C::* ptr)
     ^
static_member.cpp:31:5: error: no matching function for call to 'print_class_containing'
    print_class_containing(&object::f); // -> Not compiling
    ^~~~~~~~~~~~~~~~~~~~~~
static_member.cpp:17:6: note: candidate template ignored: couldn't infer template argument 'T'
void print_class_containing(T C::* ptr)
     ^
2 errors generated.

0 个答案:

没有答案