【问题标题】:Partially defining / aliasing a template template parameter部分定义/别名模板模板参数
【发布时间】:2020-07-15 21:07:44
【问题描述】:

我正在尝试将 CRTP 和模板模板参数与模板派生类一起使用,并在传递给基类以完全定义之前指定一些但不是全部的参数。我可以比较的最接近的概念是模板化别名,但由于它必须全部位于类定义的单顶行,我不确定如何实现这一点。希望一个例子能让它更清楚一点......

到目前为止,这是我的代码:

template<template<typename> class Template1, typename Param1>
class Base
{
public:
    using type = Param1;
};

template<template<typename, typename> class Template1, typename Param1, typename Param2>
class Derived : public Base<template<typename P1> class Template1<P1, Param2>, Param1>
{};

template<typename Param1, typename Param2>
class Template1
{};

int main()
{
  Derived<Template1, int, double>::type d = 0;
}

目前失败,原因如下:

9:89:错误:模板参数的数量错误(1,应该是 2) 2:7:错误:为“模板 类基”提供 在函数'int main()'中: 18:3:错误:'type' 不是'Derived'的成员

该错误消息真正让我感到困惑的是,我在任何地方都看不到我只指定了一个模板参数。我还发现,如果我定义 Derived 如下,那么它编译得很好:

template<typename> class Test {};

template<template<typename, typename> class Template1, typename Param1, typename Param2>
class Derived : public Base<Test, Param1>
{};

我认为这表明问题肯定出在这条线上(不出所料,我不清楚如何实现这一点):

class Derived : public Base<template<typename P1> typename Template1<P1, Param2>, Param1>

基本上,我在这里尝试使用单个参数定义一个新模板,它是第一个具有两个参数的模板的部分特化。我想我没有正确地这样做。但是我怎样才能在一条线上呢?

提前感谢您的帮助。抱歉,如果这有任何不清楚的地方!

【问题讨论】:

    标签: c++ c++11 templates crtp


    【解决方案1】:

    可能是这样的:

    template<template<typename, typename> class TwoParamTemplate, typename Param2>
    struct BindSecond {
        template <typename Param1>
        using type = TwoParamTemplate<Param1, Param2>;
    };
    
    template<template<typename, typename> class Template1,
             typename Param1, typename Param2>
    class Derived : public Base<BindSecond<Template1, Param2>::template type, Param1>
    {};
    

    Demo

    【讨论】:

    • 完美!非常感谢,这正是我需要的。
    猜你喜欢
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 2016-06-11
    相关资源
    最近更新 更多