How to create a Variant class similar to QVariant
How to create a Variant class similar to QVariant
I am trying to create a Variant class similar to Qt's QVariant. I've considered std::variant and std::any but unfortunately I need something analogous to the QVariant::value() function. But, I can't find a way to implement the function without getting errors like this:
note: candidate: template<class T> T Variant::value() const
inline T value() const {
^~~~~
note: template argument deduction/substitution failed:
note: couldn't deduce template parameter ‘T’
This answer seems to be what I want but I am trying to understand why that implementation works without receiving the "deduce template parameter 'T'" error on the return type. Any help would be greatly appreciated. Thank you.
Here's my .H:
class Variant
private:
enum VariantType
CHAR = 0,
UCHAR,
SCHAR,
SHORT,
USHORT,
INT,
UINT,
LONG,
ULONG,
LONGLONG,
ULONGLONG,
BOOL,
FLOAT,
DOUBLE,
LONGDOUBLE
;
public:
explicit Variant(int i);
explicit Variant(double d);
int ToInt() const;
double ToDouble() const;
private:
struct Internal
Internal(VariantType typeIn) :
type(typeIn)
union
char c;
unsigned char uc;
short s;
signed char sc;
unsigned short us;
int i;
unsigned int ui;
long l;
unsigned long ul;
long long ll;
unsigned long long ull;
bool b;
float f;
double d;
long double ld;
void *ptr;
value;
VariantType type;
;
Internal _data;
public:
template<typename T>
inline T value() const
// try to get int/double working first
if (_data.type == VariantType::DOUBLE)
return _data.value.d;
else if (_data.type == VariantType::INT)
return _data.value.i;
;
And here's my .CPP:
Variant::Variant(int i) : _data(INT)
_data.value.i = i;
Variant::Variant(double d) : _data(DOUBLE)
_data.value.d = d;
int Variant::ToInt() const
return _data.value.i;
double Variant::ToDouble() const
return _data.value.d;
EDIT.
use
std::variant en.cppreference.com/w/cpp/utility/variant– eyllanesc
Aug 29 at 4:42
std::variant
Also, please make sure to post an Minimal, Complete, and Verifiable example - emphasis on minimal There's a ton of code here not required to reproduce your error.
– xaxxon
Aug 29 at 4:43
@eyllanesc that's quite unhelpful. he said he already considered it.
– xaxxon
Aug 29 at 4:43
For example, you would use "Type erase". Code in stl
std::variant.– MrBin
Aug 29 at 4:46
std::variant
1 Answer
1
The error comes from your call site, not the class definition. And the error tells you that Variant::value<T>() needs a <T>, but you did not provide any type argument with which to instantiate value<T>.
Variant::value<T>()
<T>
value<T>
This same restriction applies to QtVariant, it's not unique to your class.
QtVariant
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
isn't this what std::get_if is for?
– xaxxon
Aug 29 at 4:41