Can anyone tell me what the issue is with this code? It throws an error:
cannot convert argument 1 from '_Ty' to 'const day18::BaseInstruction &'
enum Command { snd, set, add, mul, mod, rcv, jgz };
struct BaseInstruction {
Command cmd;
char reg;
BaseInstruction(Command cmd, char reg)
:cmd{cmd}, reg{reg}
{}
};
template <typename T>
struct Instruction : public BaseInstruction {
T val;
Instruction(Command cmd, char reg, T val)
:BaseInstruction(cmd, reg), val{ val }
{}
};
std::unique_ptr<BaseInstruction> getInstructionPtr(Command cmd, char reg, std::string valStr) {
const static std::regex nr("-?\\d ");
if (valStr.length() == 0) return std::make_unique<BaseInstruction>(new BaseInstruction(cmd, reg));
if (std::regex_match(valStr, nr)) return std::make_unique<BaseInstruction>(new Instruction<int>(cmd, reg, std::stoi(valStr)));
return std::make_unique<BaseInstruction>(new Instruction<char>(cmd, reg, valStr[0]));
}
CodePudding user response:
std::make_unique()
is the smart-pointer equivalent of new
, which means it calls the constructor of the specified type, passing the input parameters to that constructor, and returns a std::unique_ptr
that points to the new object.
The statement:
std::make_unique<BaseInstruction>(new Instruction<char>(...));
is therefore equivalent to this:
new BaseInstruction(new Instruction<char>(...))
I'm quite sure that's not what you meant to write.
If you just want to convert a raw pointer to a std::unique_ptr
, construct the std::unique_ptr
directly and don't use std::make_unique()
:
return std::unique_ptr<BaseInstruction>(new Instruction<char>(...));
Otherwise, use std::make_unique()
to construct Instruction<char>
instead of BaseInstruction
:
return std::make_unique<Instruction<char>>(...);