I created this class so I could have a value of any type which is either fixed or recalculated everytime it's used:
template<typename T>
class Value {
private:
bool fixed;
union {
T value;
std::function<T()> get;
};
public:
Value(const T& value) : fixed(true), value(value) {}
Value(const std::function<T()>& get) : fixed(false), get(get) {}
Value(const T *pointer) : Value([pointer]() { return *pointer; }) {}
~Value() {}
operator T() { return fixed ? value : get(); }
};
All the following expressions seem to work fine:
Value<double> a = 2.2;
double b = 1.;
double c = a;
Value<double> d = &b;
Value<int> e = Value<int>([]() { return 1.; });
But when I try to do:
Value<double> f = []() { return 1.; };
a compilation error is triggered:
error: conversion from 'main()::<lambda()>' to non-scalar type 'Value<double>' requested
You can try this example here.
Why does assigning work for T
and not std::function<T()>
and how can I make it so it does?
Note: I'm aware of this answer but I didn't become clear to me how to fix the issue without having to explicitly call the constructor like I did for Value<double> e
.
Value<int> e = Value<int>([]() { return 1; });
while the one hereValue<double> e = Value<int>([]() { return 1.; });
is an errorauto f = Value<int>([]() { return 1; });
If you are worried about spelling out the type twice. Its basically the same, and works ;)std::variant
. Also, for the first two constructors, sinceValue
wants to "takes ownership of" (i.e. saves) the argument, you should make the arguments by-value (no reference qualifier) andstd::move
them into the data members. That way, the caller controls whether to copy or to move, instead of you forcing a copy.