获取非静态方法参数计数

时间:2018-01-18 21:43:18

标签: c++

这里有一些工作答案可以计算函数所需的参数数量:Get function parameters count

使用其中一个我可以发现这需要5个参数:

void foo(const std::string&, const std::string&, const std::string&, const std::string&, const std::string&) {}

但是我想为此工作:

struct Foo {
    void foo(const std::string&, const std::string&, const std::string&, const std::string&, const std::string&) {}
};

在下面的代码中,第一个std::cout表示5,第二个是编译器错误,如果它被取消注释:

#include <iostream>
#include <string>

struct Foo {
    void foo(const std::string&, const std::string&, const std::string&, const std::string&, const std::string&) {}
};

void foo(const std::string&, const std::string&, const std::string&, const std::string&, const std::string&) {}

template <class R, class... ARGS>
struct function_ripper {
    static constexpr size_t n_args = sizeof...(ARGS);
};

template <class R, class... ARGS>
auto constexpr make_ripper(R (ARGS...) ) {
    return function_ripper<R, ARGS...>();
}

int main() {
    std::cout << decltype(make_ripper(foo))::n_args << std::endl; // 5
    //std::cout << decltype(make_ripper(Foo::foo))::n_args << std::endl; // error
    return 0;
}

这是错误:

foo.cpp: In function ‘int main()’:
foo.cpp:22:44: error: invalid use of non-static member function ‘void Foo::foo(const string&, const string&, const string&, const string&, const string&)’
     std::cout << decltype(make_ripper(Foo::foo))::n_args << std::endl;
                                            ^~~
foo.cpp:22:44: error: invalid use of non-static member function ‘void Foo::foo(const string&, const string&, const string&, const string&, const string&)’
foo.cpp:22:18: error: decltype evaluates to ‘<type error>’, which is not a class or enumeration type
     std::cout << decltype(make_ripper(Foo::foo))::n_args << std::endl;

如何做到这一点?

1 个答案:

答案 0 :(得分:3)

您可以添加另一个make_ripper函数模板来处理成员函数:

template <class C, class R, class... ARGS>
auto constexpr make_ripper(R (C::*)(ARGS...) ) {
    return function_ripper<R, ARGS...>();
}

然后称之为:

decltype(make_ripper(&Foo::foo))::n_args

EXAMPLE