What does the following template do in C++?
template <class R, class T>
struct my_type<R(*)(T)> { typedef T type; };
Specifically, what does the * stand for in this context?
In this context it makes the template specialization refer to a pointer to a function, which is declared to accept a single argument of type T
, and return a value of type R
. The specialization extracts the argument type and makes it available as a typedef.
Example (demo):
#include <iostream>
#include <type_traits>
int foo(float);
template <typename T>
struct my_type;
template <class R, class T>
struct my_type<R(*)(T)> { typedef T type; };
int main() {
std::cout
<< std::is_same<
float,
typename my_type<decltype(&foo)>::type
>::value
<< "\n";
return 0;
}
This outputs 1
because float
and typename my_type<decltype(&foo)>::type
both refer to the same type -- decltype(&foo)
is the type int (*)(float)
, which matches the specialization R(*)(T)
.