【问题标题】:Different base class depending on template parameters不同的基类取决于模板参数
【发布时间】:2019-10-04 14:59:53
【问题描述】:

是否可以在编译时根据其参数确定类模板的确切基础?例如。我有一个类模板,它在其构造函数中接受一个参数,我想用另一个参数扩展这个类,将使用另一个构造函数。问题是第二个实例化(带有两个参数)必须具有与带有一个参数的实例不同的基类。我可以使用std::conditional 检测到正确的基类,但问题在于将两个构造函数都放在一个类模板中。例如:

#include <type_traits>

struct X
{
};

struct Y
{
};

struct XX
{
};

struct XY
{
};


template<class T, class V = void>
struct Z: public std::conditional_t<std::is_void_v<V>, XX, XY>
{
    Z(T&& t, V&& v)
        : XY()
    {
        // do smth with t and v
    }

    Z(T&& t)
        : XX()
    {
        // do smth with t
    }
};

int main()
{
    auto a = Z(X(), Y());
    auto b = Z(X());         // <-- this instantiation fails
}

这里Z(X(), Y()) 可以工作,但对于Z(X()),它会因编译错误而失败:

main.cpp: In instantiation of 'struct Z<X, void>':

main.cpp:39:19:   required from here

main.cpp:23:5: error: forming reference to void

   23 |     Z(T&& t, V&& v)

      |     ^

更新:

尝试使用enable_if 将双参数ctor 设为模板,但它不起作用(与原始代码中的forming reference to void 相同):

    template<class = std::enable_if<! std::is_void_v<V>>>
    Z(T&& t, V&& v)
        : XY()
    {
        // do smth with t and v
    }

【问题讨论】:

  • 能否请您添加您尝试实例化模板的行? IE。错误消息中提到的行。
  • 在源代码列表中添加注释(第二个实例化一个参数)。
  • 这看起来像是在你的 ctor(s) 上使用 std::enable_if 的案例。
  • @Matthew:请注意,构造函数必须是 SFINAE 它的模板(即使这样,它也需要一些微妙的技巧来延迟替换失败)。
  • @davis-herring 我希望能够在不指定模板参数的情况下声明Z 的实例。

标签: c++ inheritance c++17


【解决方案1】:

不是一个优雅的解决方案,但似乎可以work,使用部分专业化和演绎指南。

template<class T, class V>
struct Z: public XY
{
    Z(T&& t, V&& v)
        : XY()
    {
        // do smth with t and v
    }
};

template<class T>
struct Z<T, void> : public XX
{
    Z(T&& t)
    : XX()
    {

    }
};

template <class T>
Z(T&& ) -> Z<T, void>;

【讨论】:

  • 这将编译。但是,看起来不可能直接重用Z&lt;T, V&gt; 中的Z&lt;T&gt; 成员,因为在定义通用模板Z&lt;T, V&gt; 之前无法引用Z&lt;T&gt; 作为模板特化。所以,如果Z&lt;T, V&gt; 的意思是“大部分类似于 Z,加上一些与 V 实例相关的次要功能”,那将不可能直接实现,或者至少我不知道如何实现。
  • @Student4K 是的,我承认这不是一个“好”的解决方案。我只是发表自己的拙见,希望能引出更好的意见。仅仅基于这个方案,如果想尽可能多地复用,可以多加一个抽象层,比如pimpl?
【解决方案2】:

高级条件类定义的常用方法是依赖基类:

struct B1 {};
struct B2 {};

template<class T>
struct Z1 : B1 {
  Z1(T&&) : B1() {}
};
template<class T,class V>
struct Z2 : B2 {
  Z2(T&&,V&&) : B2() {}
};

template<class T,class V>
using Z0=std::conditional_t<std::is_void_v<V>,Z1<T>,Z2<T,V>>;

template<class T,class V=void>
struct Z : Z0<T,V> {
  using Z0<T,V>::Z0;
};
template<class T> Z(T) -> Z<T>;
template<class T,class V> Z(T,V) -> Z<T,V>;

需要推导指南,因为 CTAD 只考虑主模板(不包括其继承的构造函数)。

如果此转换产生的Z 没有自己的成员,C++20 可能会提供直接使用(这里称为)Z0 的机会,因为它支持别名模板的 CTAD。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 2018-04-09
    • 2017-04-02
    • 2023-03-12
    • 2018-08-03
    相关资源
    最近更新 更多