I had a templated class that had a getter function and a setter function pointer. When I created an object of this class and I didn't want its setter to do anything I'd just pass nullptr as the setter function argument. Then at runtime, it would check if its setter pointer was nullptr to see whether it should call the setter.
Using a function pointer isn't good enough now because I want the class to be able to store a lambda. So instead of a function pointer the setter is now a template type argument. Before I used to pass a nullptr to signify that there was no setter, but now I can't, so I use a dummy char member, as you can see:
template <typename GetFunctionType, typename SetFunctionType = char>
class MyClass
{
public:
MyClass(GetFunctionType getFunction, SetFunctionType setFunction = char(0))
: getFunction(getFunction), setFunction(setFunction)
{}
GetFunctionType getFunction;
SetFunctionType setFunction;
typedef decltype(getFunction()) ReturnType;
void set(ReturnType value)
{
if constexpr (std::is_invocable_v<decltype(setFunction), ReturnType>)
{
setFunction(value);
std::cout << "Setter called\n";
}
else
{
// ELSE DO NOTHING
std::cout << "Object has no setter\n";
}
}
};
int main()
{
MyClass foo([]() { return 7; }, [](int val) { std::cout << "You have set the value\n"; });
MyClass foo2([]() {return 7; }); // THIS OBJECT HAS NO SETTER, BUT HAS A CHAR
// MEMBER THAT I USED AS A DUMMY
foo.set(1);
foo2.set(1);
}
My question is do I need that dummy char in cases where the object has no setter function?