Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

c++ - Determining the Parameter Types of an Undefined Function

I've recently learned that I cannot:

  1. Take the address of an undefined function
  2. Take the address of a templatized function with a type it would fail to compile for

But I've also recently learned that I can call decltype to get the return type of said function

So an undefined function:

int foo(char, short);

I'd like to know if there's a way that I can match the parameter types to the types in a tuple. This is obviously a meta programming question. What I'm really shooting for is something like decltypeargs in this example:

enable_if_t<is_same_v<tuple<char, short>, decltypeargs<foo>>, int> bar;

Can anyone help me understand how decltypeargs could be crafted?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For non-overloaded functions, pointers to functions, and pointers to member functions, simply doing decltype(function) gives you the type of the function in an unevaluated context, and that type contains all the arguments.

So to get the the argument types as a tuple, all you need are a lot of specializations:

// primary for function objects
template <class T>
struct function_args
: function_args<decltype(&T::operator()>
{ };

// normal function
template <class R, class... Args>
struct function_args<R(Args...)> {
    using type = std::tuple<Args...>;
};

// pointer to non-cv-qualified, non-ref-qualified, non-variadic member function
template <class R, class C, class... Args>
struct function_args<R (C::*)(Args...)>
: function_args<R(Args...)>
{ };

// + a few dozen more in C++14
// + a few dozen more on top of that with noexcept being part of the type system in C++17

With that:

template <class T>
using decltypeargs = typename function_args<T>::type;

This requires you to write decltypeargs<decltype(foo)>.


With C++17, we will have template <auto>, so the above can be:

template <auto F>
using decltypeargs = typename function_args<decltype(F)>::type;

and you'd get the decltypeargs<foo> syntax.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...