Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic functions (without arguments!)

Let's assume you want to do this in C++0x:

size_t count_int() { return 0; }
template<typename T, typename... Tn>
size_t count_int(T a0, Tn... an) {
    size_t n = is_integer<T>::value ? 1 : 0;
    return n + count_int(an...);
}

Nice, but it feels unnecessary to pass around the arguments. Unfortunately, this does not work:

size_t count_int() { return 0; }
template<typename T, typename... Tn>
size_t count_int() {
    size_t n = is_integer<T>::value ? 1 : 0;
    return n + count_int<Tn...>();
}

GCC complains error: no matching function for call to 'count_int()' in the next-to-last line. Why and how can this be fixed? Thanks.

like image 608
Hans Avatar asked Feb 23 '11 12:02

Hans


People also ask

Which of the functions are variadic?

Variadic functions are functions (e.g. printf) which take a variable number of arguments. The declaration of a variadic function uses an ellipsis as the last parameter, e.g. int printf(const char* format, ...);.

How do you declare a variadic function in C++?

Variadic functions are functions (e.g. std::printf) which take a variable number of arguments. To declare a variadic function, an ellipsis appears after the list of parameters, e.g. int printf(const char* format...);, which may be preceded by an optional comma.

What is variadic function in Python?

Variadic parameters (Variable Length argument) are Python's solution to that problem. A Variadic Parameter accepts arbitrary arguments and collects them into a data structure without raising an error for unmatched parameters numbers.

What is variadic parameters in Swift?

In Swift, variadic parameters are the special type of parameters available in the function. It is used to accept zero or more values of the same type in the function. It is also used when the input value of the parameter is varied at the time when the function is called.


1 Answers

This works:

template <typename T>
size_t count_int()
{
   return is_integer<T>::value ? 1 : 0;
}

template<typename T, typename T1, typename... Tn>
size_t count_int() {
    size_t n = is_integer<T>::value ? 1 : 0;
    return n + count_int<T1,Tn...>();
};
like image 145
Suma Avatar answered Oct 24 '22 22:10

Suma