I have the following code that does not compile with Qt 6.7.2 on Debian :
#include <QCoreApplication>
#include <iostream>
#include <variant>
class Foo : public QObject
{
Q_OBJECT
};
class Bar : public QObject
{
Q_OBJECT
};
struct Vis
{
void operator()(const Foo &f)
{
std::cout << "foo visitor" << std::endl;
}
void operator()(const Bar &b)
{
std::cout << "bar visitor" << std::endl;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
std::variant<Bar, Foo> v;
Foo f;
Bar b;
v = b;
std::visit(Vis{}, v);
v = f;
std::visit(Vis{}, v);
return a.exec();
}
#include "main.moc"
The error is :
error: no match for ‘operator=’ (operand types are ‘std::variant<Bar, Foo>’ and ‘Bar’)
v = b;
As a workaround it seems ok to use raw pointers to QObject's instead :
struct Vis
{
void operator()(const Foo *f)
{
std::cout << "foo visitor" << std::endl;
}
void operator()(const Bar *b)
{
std::cout << "bar visitor" << std::endl;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
std::variant<Bar *, Foo *> v;
Foo *f;
Bar *b;
v = b;
std::visit(Vis{}, v);
v = f;
std::visit(Vis{}, v);
return a.exec();
}
Am i missing something to store a QObject derived class inside a std::variant?
QObjects can not be copied.