A little library for substituting one type for another:
template<class T>struct tag{using type=T;};
template<class X, class A, class B> struct subst:tag<X>{};
template<class X, class A, class B>
using subst_t=typename subst<X,A,B>::type;
template<class A, class B> struct subst<A,A,B>:tag<B>{};
template<class X, class A, class B>
struct subst<X&,A,B>:tag<subst_t<X,A,B>&>{};
template<class X, class A, class B>
struct subst<X&&,A,B>:tag<subst_t<X,A,B>&&>{};
template<class X, class A, class B>
struct subst<X const,A,B>:tag<subst_t<X,A,B>const>{};
template<class X, class A, class B>
struct subst<X volatile,A,B>:tag<subst_t<X,A,B>volatile>{};
template<class X, class A, class B>
struct subst<X const volatile,A,B>:tag<subst_t<X,A,B>const volatile>{};
template<template<class...>class Z,class...Xs, class A, class B>
struct subst<Z<Xs...>,A,B>:tag<Z<subst_t<Xs,A,B>...>>{};
template<template<class,size_t>class Z,class X,size_t n, class A, class B>
struct subst<Z<X,n>,A,B>:tag<Z<subst_t<X,A,B>,n>>{};
template<class R,class...Xs, class A, class B>
struct subst<R(Xs...),A,B>:tag<subst_t<R,A,B>(subst_t<Xs,A,B>...)>{};
now we use it:
struct own_type {};
template<class Sig>
struct recursive_func{
using func=std::function< subst_t<Sig, own_type, recursive_func> >;
template<class...Ts>
std::result_of_t<func const&(Ts...)>
operator()(Ts&&...ts)const{
return f(std::forward<Ts>(ts)...);
}
operator func const&()const&{return f;}
operator func&()&{return f;}
operator func()&&{return std::move(f);}
template<class F,
class=std::enable_if_t<
!std::is_same<recursive_func,std::decay_t<F>>::value
&& std::is_convertible<F,func>::value
>
>
recursive_func(F&&fin):f(fin){}
func* operator->(){return f;}
func const* operator->()const{return f;}
private:
func f;
};
which gives you a lovely syntax:
recursive_func< std::vector<own_type>() > f;
is a function that returns a vector of its own type.
This uses a smattering of C++14 _t
aliases. std::blah_t<?>
can be replaced with typename std::blah<?>::type
if your compiler is strictly C++11. There may be other typos.
A weakness is that templates that expect their types to satisfy some property in the immediate context may fail when fed own_type
. This can be fixed with a delayed template applicator that subst
understands, but in casual use is unlikely to be a problem.
live example