简体   繁体   English

推导(非)模板类型的签名

[英]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. 问题是这样的:我正在开发一个数学库,它有很多函数,比如确定整数或std :: initializer_list的优先级,将整数改为罗马数字等等。 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). 因此,我决定编写apply ,使其不必看起来像上面的直接丑陋代码(确切地说是案例2 )。 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. 现在,我没有想法,我知道我可以在应用中使用std :: function但我不想使用它,除非没有别的办法。 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. 请不要误解我的意思,我不是说std​​ :: function在这里不适用,我只是说我会,当且仅当我没有任何其他选择时。

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. 注意:数学库是一个侧面项目,我用它来教我的大学伙伴C ++如何做事情,因此我较少使用一些高级概念。

Here's implementation of apply that works with function pointers or callable classes such as lambdas and deduces template parameters: 这里的apply的实现适用于函数指针或可调用的类,如lambdas和推导模板参数:

#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)...);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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