I wanted to have type traits which will help me to get the type of the class from a member function pointer. I looked into this answer and found my half way to the aim.
It looks like this:
#include <iostream>
// example class
struct MyClass {
void funct() { std::cout << "funct has been called....\n"; }
};
// traits
template<typename Class> struct get_class{};
template<typename ReType, typename Class, typename... Args>
struct get_class<ReType(Class::*)(Args...)>
{
using type = Class;
};
template<typename Type> using get_class_t = typename get_class<Type>::type;
int main()
{
get_class_t<decltype(&MyClass::funct)> myObj;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ---> this is a lot of typing
myObj.funct();
return 0;
}
But, as shown in the code I need every time to write get_class_t<decltype(&MyClass::funct)>
or in the case of
auto ptr = &MyClass::funct;
get_class_t<decltype(ptr)> myObj;
// ^^^^^^^^^^^^^^
which is a lot of decltype()
ing. I would like to write instead
class_t<ptr> obj;
or
class_t<&MyClass::funct> myObj;
which is more convenient.
I did the following function, which will return a resulting object of the class and maybe I could do, want I wanted to.
template<typename Type>
auto helper_function(Type ptr)->get_class_t<Type>
{
return get_class_t<Type>{};
}
template<typename Type>
using class_t = /* decltype(helper_function(Type ptr));*/
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // what could be here?
I do not know how to complete this. My goal is to extend the traits in such a way that I could create an object like
auto ptr = &MyClass::funct;
class_t<ptr> myObj;
// or
class_t<&MyClass::funct> myObj;
Is there any other way to do this? or should I have to stick with decltype()
ing?
As I have tagged, I would like to see whether it possible with C++11?