Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int(int, int) style template function type syntax

I remember that when using Boost.Spirit and for the std::function addition to C++0x, you specify the function type by using a syntax that doesn't use pointers, like in defining std::function<bool(int)> fn, whereas you would cast a pointer like (bool(*)(int))fn.

Can anyone tell me the name of this new syntax or any references on this, or how to use it? It seems like a polymorphic function type syntax that applies for functors as well, but I don't really know how to use it.

like image 915
norcalli Avatar asked Aug 11 '11 14:08

norcalli


People also ask

What is the syntax of function template?

A function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.

What is the correct syntax of defining function template template functions?

What is the correct syntax of defining function template/template functions? Explanation: Starts with keyword template and then <class VAR>, then use VAR as type anywhere in the function below. 7.

What is the syntax of class template?

1. What is the syntax of class template? Explanation: Syntax involves template keyword followed by list of parameters in angular brackets and then class declaration.

What is type template C++?

A template is a simple yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types.


2 Answers

bool(int) is the type of the function; bool(*)(int) is the type of the function pointer. In other words, if you define

typedef bool(BF)(int);
typedef bool(pBF*)(int);

then BF* is the same as pBF.

The std::function template captures the return and argument types via (variadic) templates:

template <typename R, typename ...Args> struct function
{
  function(R(&f)(Args...)); // conceptually
}
like image 159
Kerrek SB Avatar answered Oct 20 '22 22:10

Kerrek SB


It is not new sintax, although old compilers did sometimes reject it. It is simply the type of a function versus the type of a function pointer, similar to the type of an arrays versus the pointer to an array.

The facts that there are no function l-values and that function r-values decay quickly to pointer-to-functions make them mostly useless. Except in the case of templates, of course.

like image 32
rodrigo Avatar answered Oct 20 '22 23:10

rodrigo