gpt4 book ai didi

c++ - 我如何 curry 可变参数模板模板参数?

转载 作者:可可西里 更新时间:2023-11-01 16:42:29 25 4
gpt4 key购买 nike

Variadic 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>;

我想要 Currying template 模板类。
这意味着:如果参数接受一个模板参数作为 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!
};

最佳答案

简单的解决方案是:

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...>;
};

但由于编译错误(至少在 gcc 下),它不适用于 Test1Test2 等模板。此问题的解决方法如下所示:

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

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

现在行

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

应该换成行

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

使用示例:

#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<>{});

完整示例位于 ideone .

关于c++ - 我如何 curry 可变参数模板模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21406726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com