I have been using C++ template class partial specialization for function argument for a while. I was surprised to find that the same syntax could be used to partial specialize functors.
In the case 1 below, it is easy to see F(T) is a function type. Since it is a type, it could be used to substitute the template parameter, however in case 2, the semantics of F(T) is changed, it is not a type but still can pass the compiler and work.
I googled a few hours, but not found too much valuable info in this regard. Could anyone explain why case 2 worked?
template<class> struct func;
template<class F, class T>
struct func<F(T)> //1. this is a partial specialization for function
{ //with signature F(T)
using type = F(T);
};
template<class> struct ftor;
template<class F, class T>
struct ftor<F(T)> //2. Is F(T) a type?
{
using type = F;
};
struct foo {
void operator()(int) {}
};
int main() {
//1 void(int) is a function signature
cout<<typeid(typename func<void(int)>::type).name()<<endl;
//2 what is foo(int)?
cout<<typeid(typename ftor<foo(int)>::type).name()<<endl;
return 0;
}
In the 2 cases, F(T)
is a signature of function taking T
and returning F
.
You may rename your class func
by identity
and ftor
by result_of
and F
by ReturnType
to better match naming/implementation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.