简体   繁体   中英

Deducing signature of (non-)templated types

I'm relatively new to writing template metaprogramming, it's probably the reason I couldn't find a solution to this problem. The problem is this: I'm developing a mathematics library, with so many functions like determining the primeness of an integer or std::initializer_list, changing integers to roman numerals among many other things. The bottleneck started when I tried to implement a generic function that returns the result of a function call such that:

apply( foo, 1 ) === foo( 1 );

For template functions, it wouldn't make any sense if it's written like so:

apply( foo<int, int, int...>, 1, 2, 3... ); //Case 1
apply<int, int, double...>( foo, 1, 2, 3...) // Case 2
//OR whichever flavours the (closure object or ) callable has.

So I decided to write apply such that it does not have to look like the immediate ugly code above( case 2 to be precise). I landed here at first and then I thought that was incorrect, then I rewrote it again here .

Right now, I'm out of ideas and I know well I could make use of std::function in apply but I don't wanna use it unless there's no other way. Please don't get me wrong, I'm not saying std::function is not applicable here, I'm just saying I will, if and only if I don't have any other option.

NOTE: The math library is a side project I use to teach my college mates how C++ does things, therefore I make lesser use of some advanced concepts.

Here's implementation of apply that works with function pointers or callable classes such as lambdas and deduces template parameters:

#include <type_traits>
#include <utility>

template<class Fun, class... Args>
typename std::result_of<Fun(Args...)>::type
apply(Fun&& fun, Args&&... args)
{
    return fun(std::forward<Args>(args)...);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM