Jon*_*Mee 12 c++ methods templates member-function-pointers metatype
给定一个对象:
struct foo {
void func();
};
Run Code Online (Sandbox Code Playgroud)
现在给出模板化的函数声明:
template<typename T, T F>
void bar();
Run Code Online (Sandbox Code Playgroud)
所以bar将采用这样的成员函数:
bar<decltype(&foo::func), &foo::func>()
Run Code Online (Sandbox Code Playgroud)
在机身的bar我要恢复的数据类型foo的T.我能这样做吗?我希望能够做到这样的事情:
get_obj<T> myfoo;
(myfoo.*F)();
Run Code Online (Sandbox Code Playgroud)
我知道这get_obj不是一件事,但有没有办法写出来?
Yak*_*ont 13
template<class T>
struct get_memfun_class;
template<class R, class T, class...Args>
struct get_memfun_class<R(T::*)(Args...)> {
using type=T;
};
template<class T>
using get_memfun_class_t=typename get_memfun_class<T>::type;
template<auto M>
using class_of_memfun = get_memfun_class_t< decltype(M) >;
Run Code Online (Sandbox Code Playgroud)
class_of_memfun<F>然后是成员函数的类F.
要处理const/volatile/etc,你最终不得不做一堆版本.这很烦人.这是一个例子:
template<class T>
struct get_memfun_class;
#define GET_MEMFUN_CLASS(...) \
template<class R, class T, class...Args> \
struct get_memfun_class<R(T::*)(Args...) __VA_ARGS__> { \
using type=T; \
}
Run Code Online (Sandbox Code Playgroud)
可能你想要:
template<class R, class T, class...Args> \
struct get_memfun_class<R(T::*)(Args...) __VA_ARGS__> { \
using type=T __VA_ARGS__; \
}
Run Code Online (Sandbox Code Playgroud)
指向const memfun的指针类的类型是否为const类?
一旦你选择了,你需要写上面宏的24次使用:
GET_MEMFUN_CLASS();
GET_MEMFUN_CLASS(const);
GET_MEMFUN_CLASS(volatile);
GET_MEMFUN_CLASS(const volatile);
GET_MEMFUN_CLASS(&);
GET_MEMFUN_CLASS(const&);
GET_MEMFUN_CLASS(volatile&);
GET_MEMFUN_CLASS(const volatile&);
GET_MEMFUN_CLASS(&&);
GET_MEMFUN_CLASS(const&&);
GET_MEMFUN_CLASS(volatile&&);
GET_MEMFUN_CLASS(const volatile&&);
GET_MEMFUN_CLASS(noexcept);
GET_MEMFUN_CLASS(const noexcept);
GET_MEMFUN_CLASS(volatile noexcept);
GET_MEMFUN_CLASS(const volatile noexcept);
GET_MEMFUN_CLASS(& noexcept);
GET_MEMFUN_CLASS(const& noexcept);
GET_MEMFUN_CLASS(volatile& noexcept);
GET_MEMFUN_CLASS(const volatile& noexcept);
GET_MEMFUN_CLASS(&& noexcept);
GET_MEMFUN_CLASS(const&& noexcept);
GET_MEMFUN_CLASS(volatile&& noexcept);
GET_MEMFUN_CLASS(const volatile&& noexcept);
#undef GET_MEMFUN_CLASS
template<class T>
using get_memfun_class_t=typename get_memfun_class<T>::type;
Run Code Online (Sandbox Code Playgroud)
我不知道如何避免完全覆盖所有这24项专业化.如果你认为这是愚蠢的,那你就是对的; 请随意通过向C++标准委员会提出修正来表达您的烦恼.
如果你为不止一个特性做这样的事情,你可以在一个地方写下"剥离左值,右值,无法和cv限定符"并将它们分成几部分.
实例.
如果您限制为void(T::mem_fun)():
#include <iostream>
struct foo {
void func(){ std::cout << "foo"; }
};
template <typename T> struct get_type;
template <typename T> struct get_type<void(T::*)()> {
using type = T;
};
template <typename T> using get_type_t = typename get_type<T>::type;
template<typename T, T F> void bar(){
get_type_t<T> myfoo;
(myfoo.*F)();
}
int main () {
bar<decltype(&foo::func), &foo::func>();
}
Run Code Online (Sandbox Code Playgroud)