如何不同地调用函数对象,取决于它的arity(或编译时已知的其他信息)? [英] How to call a function object differently, depending on its arity (or other information known at compile time)?

查看:229
本文介绍了如何不同地调用函数对象,取决于它的arity(或编译时已知的其他信息)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在函数模板中,我想调用一个函数或函数对象,具体取决于它的arity(需要多少参数)。在伪码中:

  if arity(f)== 1:
f(x)
如果arity f)== 2:
f(x,y)
if arity(f)== 3:
f(x,y,z)



如何在C ++中完成此操作?



澄清困难: f 只有2个参数,则 f(x,y,z)反之亦然, f 需要3个参数时, f(x,y) b $ b

解决方案

使用C ++ 11:

  #include< iostream> 

template< typename F> struct Traits;

template< typename R,typename ... A>
struct Traits< R(A ...)>
{
static constexpr unsigned Arity = sizeof ...(A);
};

void f(int,int,int);

int main(){
std :: cout
<< Traits< void()> :: Arity
<< Traits< void(int)> :: Arity
<< Traits< void(int,int)> :: Arity
<< Traits< decltype(f)> :: Arity
<< '\\\
';
return 0;
}

否则可以查找boost :: function: http://www.boost.org/doc/libs/1_55_0b1/doc/html/function。 html


In a function template, I'd like to call a function, or function object differently, depending on its arity (how many arguments it takes). In pseudocode:

if arity(f) == 1:
    f(x)
if arity(f) == 2:
    f(x, y)
if arity(f) == 3:
    f(x, y, z)

How can this be done in C++?

Edit To clarify the difficulty: f(x, y, z) won't compile if f only takes 2 arguments, and vice versa, f(x, y) won't compile when f needs 3 arguments.

解决方案

With C++11:

#include <iostream>

template <typename F> struct Traits;

template <typename R, typename... A>
struct Traits<R (A...)>
{
    static constexpr unsigned Arity = sizeof...(A);
};

void f(int, int, int);

int main() {
    std::cout
        << Traits<void()>::Arity
        << Traits<void(int)>::Arity
        << Traits<void(int, int)>::Arity
        << Traits<decltype(f)>::Arity
        << '\n';
    return 0;
}

Otherwise you might lookup boost::function: http://www.boost.org/doc/libs/1_55_0b1/doc/html/function.html

这篇关于如何不同地调用函数对象,取决于它的arity(或编译时已知的其他信息)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆