fe2*_*263 9 c++ templates variadic-templates c++11
可变参数模板模板参数接受任何模板:
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>;
Run Code Online (Sandbox Code Playgroud)
我想要Currying模板模板类.
这意味着:如果参数接受一个模板参数Test1,curry::apply<T>::type get Test1<T>::type.如果参数接受两个模板参数Test2,curry2::apply<T0>则为"部分"模板,curry2::apply<T0>::apply<T1>::type get Test2<T0,T1>::type
这有可能实现吗?因为我无法查询模板模板参数的内部参数num:
template<template<typename... S> class BeCurry>
struct Currying {
enum { value = sizeof...(S) }; // error!
};
Run Code Online (Sandbox Code Playgroud)
简单的解决方案是:
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...>;
};
Run Code Online (Sandbox Code Playgroud)
但由于编译错误(至少在gcc下),它不适用于Test1和等模板。此问题的解决方法如下所示:Test2
template
<
template <typename...> class BeCurry,
typename... Params
>
struct Curry
{
using type = BeCurry<Params...>;
};
template
<
template <typename...> class BeCurry
>
struct Curry<BeCurry>
{
using type = BeCurry<>;
};
Run Code Online (Sandbox Code Playgroud)
现在线路
template <typename... OtherParams>
using curried = BeCurry<Params..., OtherParams...>;
Run Code Online (Sandbox Code Playgroud)
应该用线条代替
template <typename... OtherParams>
using curried = typename Curry<BeCurry, Params..., OtherParams...>::type;
Run Code Online (Sandbox Code Playgroud)
使用示例:
#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<>{});
Run Code Online (Sandbox Code Playgroud)
完整示例位于ideone。
| 归档时间: |
|
| 查看次数: |
961 次 |
| 最近记录: |