【发布时间】:2018-08-25 20:41:59
【问题描述】:
我想让我的课程能够在std::variant 中使用。
应该工作的简单代码是:
int main()
{
std::variant< int, A > v;
A a(1);
v = a;
}
我的类包含一个模板化的构造函数:
template <typename T> A( T& );
此时麻烦开始了!构造函数绑定到来自std::variant 的调用,不再使用提供的A(const A&)。
出于复制和粘贴原因,此处的完整示例:
#include <iostream>
#include <variant>
class A
{
private:
int x;
public:
A( A&&) {}
A( const A& ) {}
A(){}
~A() {}
A& operator=( const A& ) { return *this;}
A& operator=( A&& ) {return *this;}
template <typename T>
A( T& t )
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
A(int _x):x{_x}{}
};
int main()
{
std::variant< int, A > v;
A a(1);
v = a;
}
背景:
为什么是这里的模板? 当使用采用序列化器类型的构造函数时,问题就开始了。序列化程序可以有多种类型,取决于要序列化的文件或流。
备注:我知道缺少构造函数的功能!
【问题讨论】:
-
关于您自己的代码的问题,“为什么要在此处使用模板?”,您从哪里获得此代码?
-
关于“A(A&); 使用类作为 std::variant 的元素的要求”,没有这个要求。
-
−1 缺少必需的标头。
-
@Cheersandhth.-Alf: 完成;)
-
谢谢。删除了负 1。
标签: c++ c++17 variant requirements