“Partial application” for template parameters
I hav开发者_运维知识库e the following “main” template:
template <
template <typename> class S
> struct TT { /*...*/ };
and the template I want to use with TT
:
template <int N, typename T> struct S1 {};
In particular, I want to use something like
TT< S1<5> > t2; // "Invalid template arguments" here
It is a kind of partial application for templates. I know that Boost.MPL involves this kind of stuff. The problem is that I already have some code using TT and templates like
template <typename T> struct S2 {}; // S3, S4…
which are fed to TT.
So the question is: how can I use S1
with TT
with smallest modifications to existing code. If it is mandatory to use Boost.MPL please show me most suitable solution.
Define a class template deriving from S1
as:
template <typename T>
struct S11 : S1<5,T>
{
};
And then use S11
, instead of S1
as:
TT< S11> t2; //it is as if TT< S1<5> > t2
Working code : http://ideone.com/y2s7n
Reading your comment, it seems you need this:
template<int N>
struct Magic
{
template <typename T>
struct S11 : S1<N,T>
{
};
};
//Usage
TT<Magic<5>::S11> t2;
Magic Demo : http://ideone.com/4yxvK
you can also write a generic partial application facility:
template <template <typename ...> class TT, typename... Args>
struct Apply
{
template <typename... Rest>
struct T : TT < Args..., Rest... >
{
};
};
or like this if you want the result time of the application to be the original template's specializations instead of a derived class (of a derived class, etc.):
template <template <typename ...> class TT, typename... Args>
struct Apply
{
template <typename... Rest>
struct _T
{
typedef TT < Args..., Rest... > type;
};
template <typename... Rest>
using T = typename _T < Rest... >::type ;
};
精彩评论