Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I curry variadic template template parameters?

Variadic template template parameters accept any template:

template<typename T>
struct Test1 {
    using type = int;
};

template<typename T, typename T1>
struct Test2 {
    using type = char*;
};

template<template<typename...S> class BeCurry>
struct Currying {
};

using curry  = Currying<Test1>;
using curry2 = Currying<Test2>;

I want Currying template template class.
It means: if the parameter accepts one template param as Test1, curry::apply<T>::type get Test1<T>::type. If the paramter accepts two template params as Test2, curry2::apply<T0> is a 'Partial' template, curry2::apply<T0>::apply<T1>::type get Test2<T0,T1>::type

Is this possible to implement? Because I can't query inner parameter num of template template parameters:

template<template<typename... S> class BeCurry>
struct Currying {
    enum { value = sizeof...(S) }; // error!
};
like image 446
fe263 Avatar asked Jan 28 '14 13:01

fe263


1 Answers

Simple solution is:

template
    <
        template <typename...> class BeCurry,
        typename... Params
    >
struct Currying
{
    template <typename... OtherParams>
    using curried = BeCurry<Params..., OtherParams...>;

    template <typename... OtherParams>
    using type = typename curried<OtherParams...>::type;

    template <typename... NewParams>
    using apply = Currying<curried, NewParams...>;
};

But it does not work with templates like Test1 and Test2 due to compilation errors (under gcc, at least). A workaround for this problem looks like this:

template
    <
        template <typename...> class BeCurry,
        typename... Params
    >
struct Curry
{
    using type = BeCurry<Params...>;
};

template
    <
        template <typename...> class BeCurry
    >
struct Curry<BeCurry>
{
    using type = BeCurry<>;
};

And now lines

template <typename... OtherParams>
using curried = BeCurry<Params..., OtherParams...>;

should be replaced with lines

template <typename... OtherParams>
using curried = typename Curry<BeCurry, Params..., OtherParams...>::type;

Example of using:

#include <iostream>
#include <typeinfo>

template <typename T>
void print_type(T t)
{
    std::cout << typeid(t).name() << std::endl;
}

// ...

print_type(Currying<Test1>::type<int>{});
print_type(Currying<Test1>::apply<int>::type<>{});
print_type(Currying<Test2>::type<int, char>{});
print_type(Currying<Test2>::apply<int>::type<char>{});
print_type(Currying<Test2>::apply<int>::apply<char>::type<>{});
print_type(Currying<Test2>::apply<int, char>::type<>{});

Full example at ideone.

like image 187
Constructor Avatar answered Sep 29 '22 08:09

Constructor