With the code below, I'm getting:
In static member function ‘static std::shared_ptr<std::variant<MyClass<InputClass1>, MyClass<InputClass2> > > MyCreatorClass::create()’:
main.cpp:34:57: error: could not convert ‘std::make_shared(_Args&& ...) [with _Tp = MyClass; _Args = {}]()’ from ‘shared_ptr>’ to ‘shared_ptr, MyClass >>’
Code:
#include <iostream>
#include <variant>
#include <memory>
using namespace std;
struct InputClass1{
static std::string MyName(){
return "InputClass1";
}
};
struct InputClass2{
static std::string MyName(){
return "InputClass2";
}
};
template<class InputClass>
class MyClass{
public:
MyClass(){
std::cout<<InputClass::MyName();
}
};
class MyCreatorClass{
using VariantType = std::variant<MyClass<InputClass1>, MyClass<InputClass2>>;
public:
static std::shared_ptr<VariantType> create(){
return std::make_shared<MyClass<InputClass2>>();
} // Am I using the variant the right way here?
};
int main()
{
cout<<"Hello World";
MyCreatorClass::create();
return 0;
}
CodePudding user response:
static std::shared_ptr<VariantType> create()
this is a function that returns a shared pointer to a variant over MyClass<InputClass1>, MyClass<InputClass2>
.
{
return std::make_shared<MyClass<InputClass2>>();
}
this is a function body that returns a shared pointer to a MyClass<InputClass2>
.
These two types are unrelated.
A pointer to a X
cannot be converted to a pointer to a variant
which includes an X
. Your code basically requests this to happen.
It is possible you want a variant over shared pointers instead of a shared pointer of a variant.
It is possible you want to make a shared pointer to a variant, and initialize it with a specific alternative.
Both of these are allowed. What you are doing is not.
In pseudo code, you have a sp[var[A|B]]
and are initializing it with a sp[A]
. You need to either use the type var[sp[A]|sp[B]]
or you need to initialize it with a sp[var[A]]
to be structurally compatible.
...
Finally, I see some bad signs. The default use of shared_ptr
is a bad sign, especially if you don't understand how C pointer types well enough to see the problem here. Shared lifetime management and ownership of mutable objects seems like it makes problem simpler, but really it hides problems until your system is more complex, and then makes it very difficult to track down why you have a problem.