関数の引数の数を取得する方法がC++ 11にあるかどうか疑問に思っていますか?関数のパラメータ数を取得する
は、例えば機能foo
のために私はargCount
は事前に3
#include <iostream>
void foo(int a, int b, int c)
{
}
int main()
{
size_t argCount=MAGIC(foo);
return 0;
}
感謝したいです。
関数の引数の数を取得する方法がC++ 11にあるかどうか疑問に思っていますか?関数のパラメータ数を取得する
は、例えば機能foo
のために私はargCount
は事前に3
#include <iostream>
void foo(int a, int b, int c)
{
}
int main()
{
size_t argCount=MAGIC(foo);
return 0;
}
感謝したいです。
あなたは可変引数関数テンプレートを使用して、その情報を得ることができます。
#include <iostream>
template <typename R, typename ... Types> constexpr size_t getArgumentCount(R(*f)(Types ...))
{
return sizeof...(Types);
}
//----------------------------------
// Test it out with a few functions.
//----------------------------------
void foo(int a, int b, int c)
{
}
int bar()
{
return 0;
}
int baz(double)
{
return 0;
}
int main()
{
std::cout << getArgumentCount(foo) << std::endl;
std::cout << getArgumentCount(bar) << std::endl;
std::cout << getArgumentCount(baz) << std::endl;
return 0;
}
出力:
3
0
1
はそれがhttp://ideone.com/oqF8E8で働いて参照してください。 、あなたが使用して引数の数を取得することができます。これにより
template <typename R, typename ... Types>
constexpr std::integral_constant<unsigned, sizeof ...(Types)> getArgumentCount(R(*f)(Types ...))
{
return std::integral_constant<unsigned, sizeof ...(Types)>{};
}
:
を更新
バリーの使用を示唆し
// Guaranteed to be evaluated at compile time
size_t count = decltype(getArgumentCount(foo))::value;
または
// Most likely evaluated at compile time
size_t count = getArgumentCount(foo).value;
これはいくつかの理由で実際には意味をなさない。
これは本当に良いでしょうか?何らかのリフレクションを探しているかもしれませんが、それは(まだ)C++には存在しません。これは意味がありません
主な理由は、しかし、過負荷セットです:
void f(int);
void f(int, int);
std::cout << MAGIC(f); // what should this print??
はい、簡単に行うことができます:
#include <cstddef>
#include <iostream>
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...>();
}
void foo(int, double, const char*);
void check_args() {
constexpr size_t foo_args = decltype(make_ripper(foo))::n_args;
std::cout << "Foo has " << foo_args << " arguments.\n";
}
どのような目的に適していますか? –
@πάνταῥεῖ、重いメタプログラミングでこれを少なくとも1つのアプリケーションで知っています – SergeyA
引数の数が異なる複数のオーバーロードがある場合、返されるMAGICとは何ですか? –