I created the following class to create values of any type which are either fixed or recalculated everytime the call operator is used on them:
template <typename T>
class DynamicValue {
private:
std::variant<T, std::function<T()>> getter;
public:
DynamicValue(const T& constant) : getter(constant){};
template <typename F, typename = std::enable_if_t<std::is_invocable_v<F>>>
DynamicValue(F&& function) : getter(function) {}
DynamicValue(const T* pointer) : DynamicValue([pointer]() { return *pointer; }) {}
DynamicValue(const DynamicValue& value) : getter(value.getter) {}
~DynamicValue() {}
DynamicValue& operator=(const DynamicValue& value) {
getter = value.getter;
return *this;
}
T operator()() {
return getter.index() == 0 ? std::get<T>(getter) : std::get<std::function<T()>>(getter)();
}
};
I also wrote the following dummy struct to showcase my issue:
struct A {
int b;
};
The problem is, ideally, I'd be able to initialize any DynamicValue<T>
as if it were of type T
. So, in this example, because I can do A a = {1};
, instead of having to write DynamicValue<A> a = A{1};
, I'd be able to do DynamicValue<A> a = {1};
. However, when I attempt to do so, I get the folowing error:
could not convert '{1}' from '' to 'DynamicValue'
You can try a live example here.
Is there anyway to overcome this issue or must I accept the longer syntax?