I was reading about std::function
in part 3 this (long) answer on callbacks in C++ https://stackoverflow.com/a/28689902/3832877 and it demonstrates the use template arguments which have additional types in parentheses. Examples of what I mean:
std::function<int(int, float)> foo; //for a function returning int with one int and one float argument
std::function<int(C const &, int)> moo; //from the above thread, for member function of class C taking one int argument and returning int
I understand the usage in std::function
to define the function signature, but I don't understand how the compiler is parsing these template arguments. What do the types in the parentheses mean to the compiler? Are there any other uses for this syntax or was it created specifically for std::function
and related STL classes? Can I write my own classes that use this syntax?
Those are types of functions. int(int,int)
is the type of a function that takes two int
parameters and returns an int
.
For demonstration, consider this example:
#include <type_traits>
#include <iostream>
int foo(int,int){ return 42;}
int main(){
std::cout << std::is_same< decltype(foo), int(int,int)>::value;
}
It compares the type of foo
with the type int(int,int)
, and indeed the output is 1
.
See also here: https://en.cppreference.com/w/cpp/language/function
The type of the function being declared is composed from the return type (provided by the decl-specifier-seq of the declaration syntax) and the function declarator
noptr-declarator ( parameter-list ) cv(optional) ref(optional) except(optional) attr(optional) (1) noptr-declarator ( parameter-list ) cv(optional) ref(optional) except(optional) attr(optional) -> trailing (2) (since C++11)
Can I write my own classes that use this syntax?
Yes you can. In a nutshell, int(int,int)
is just a type like others:
#include <iostream>
template <typename T>
void foo(T t){
t(42);
}
void bar(int x) { std::cout << x; }
int main() {
foo< void(int) >(bar);
// ... or ...
using fun_type = void(int);
foo< fun_type >(bar);
}