gpt4 book ai didi

c++ - std::variant of template specializations 转换 move 构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:40:40 26 4
gpt4 key购买 nike

我正在使用一个封装了模板特化的 std::variant 的类,例如:

template<typename Type> struct Generic_node {...};
struct Leaf_node : Generic_node<...> {...};
struct Inner_node : Generic_node<...> {...};

struct Node {std::variant<Leaf_node, Inner_node> variant_;};

我正在尝试构建一个 Node来自 Generic_node 中的函数使用转换 move 构造函数,但编译失败。

我定义了一个模板构造函数,它接受一个右值引用(假设是一个专门的类)并通过将值 move 到变体来构造变体,我希望在其中调用转换 move 构造函数 # (4) .

当我尝试创建最小的非工作示例时,我发现问题实际上只显示在模板函数中,如果我知道确切的类型(编译器知道的 Leaf_node == Generic_node<...>), move 构造就会成功.因此,我假设一如既往地发生了一些我没有预料到的模板魔法。

#include <variant>

template<typename T>
struct Base
{
void f();
};

struct Derived : Base<int> {};

struct Variant
{
// In real program expecting the T to be one of the multiple variants
// Here I use only one variant because it suffices to illustrate the problem
template<typename T>
Variant(T&& t)
:
variant_ {std::move(t)}
{
}

std::variant<Derived> variant_;
};

template<typename T>
void
Base<T>::
f()
{
Variant {std::move(Derived {})}; // can call on exact type
Variant {std::move(Base<T> {})}; // can not call on specialized template type
}

int
main()
{
Derived {}.f();
}

相关编译错误信息(clang 7, libstdc++-8):

note: candidate template ignored: substitution failure [with _Tp = Base<int>,
$1 = void, $2 = void]: implicit instantiation of undefined template
'std::variant<Derived>::__to_type_impl<18446744073709551615, false>'
variant(_Tp&& __t)

问题很可能与变体无关,而是与 Base<T> == Derived 的相等性有关在 Variant 构造函数的模板实例化中,编译器好像没有看到它。

模板实例化中发生了什么,为什么编译器不能调用提供的构造函数?

编辑: 因为我打算创建一个专门化,所以我忘记了继承不能暗示类类型相等,即使在技术上是在这种特殊情况下。因此,通过从专门的 Base move 来构建 Derived 是一项简单的任务:

struct Derived : Base<int>
{
Derived() = default;
Derived(Base<int>&&) {}
};

如果我是正确的,则需要为 Base 的每个派生类显式定义构造函数。

最佳答案

在您给出的示例中,Derived 类是一个独立于 Base 的类。它们具有完全相同的成员、相同的方法,但它们仍然是独立的类。

解决它的最简单方法是使用 using 语句而不是将其声明为单独的类:

using Derived = Base<int>;

关于c++ - std::variant of template specializations 转换 move 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51429511/

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