Martin Perry Martin Perry - 28 days ago 10
C++ Question

C++11 - std::declval<T>() name of method

Is there a way, how to pass a method name as template parametr after

std::declval<T>()
?

So far, I have this:

template<typename T, typename ... Args>
struct MethodInfo
{
using type = decltype(std::declval<T>().foo(std::declval<Args>() ...)) (T::*)(Args ...);
};


But I would like the "
foo
" to be template parametr.

Answer

It's not exactly what you asked but I think this may somewhat fit your need:

#include <type_traits>
#include <tuple>
#include <iostream>

template<typename T, typename... Args>
struct MethodInfo {
    template<typename Ret>
    static auto get(Ret(T::*)(Args...)) -> Ret(T::*)(Args...);
};

struct Foo {
    int foo(int);
    int foo(int, int);
};

int main() {  
    static_assert(std::is_same<
                        int(Foo::*)(int), 
                        decltype(MethodInfo<Foo, int>::get(&Foo::foo))
                          >::value, "");
}

Demo

Because, the function name is a non-type template parameter, I think this is the only solution, up to now.

Comments