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.