Set Values With Imgui::Slider Over Getter and Setter Functions

A picture of the author, Jakob Maier
Jakob Maier
Mar 30, 2024

ImGui is a very popular immediate mode GUI library used by many game developers for rapid prototyping. For me, some of the most useful features are the ImGui::Slider* family of functions, that allow for setting of values via sliders, as the name implies.

These functions can be used like this:

float value = 5.0f;

ImGui::SliderFloat("Set value", &value, 0.0f, 10.0f);


In this case, we can use the slider to set value to between 0 and 10. But what if value is a private member of a class and can only be accessed via getters and setters? Well for this reason, I have created a simple helper function:

namespace ImGui

template <typename T, typename Getter, typename Setter>
void SliderFloat(const char* label, T* t, Getter getter, Setter setter, float min, float max,
                             const char* format = "%.3f")
  float current = (t->*getter)();
  float new_value = current;

  ImGui::SliderFloat(label, &new_value, min, max, format);

  if (current != new_value) {

I put it in the ImGui namespace so we can access this function in the same way we use all other ImGui functions.

Say we now have a class Foo with a private member and some getters and setters:

class Foo {
    float value() const { return m_value; }
    void set_value(float value) { m_value = value; }
    float m_value = 5.0f;

We can now use our function to set the value via these setters and getters:

Foo foo;

ImGui::SliderFloat("Set value", &foo, &Foo::value, &Foo::set_value, 0.0f, 10.0f);

This function can of course be adapted for the other sliders such as ImGui::SliderFloat3, ImGui::SliderInt and so on, but this is left as an exercise for the reader.

↑ back to top

© 2023 Jakob Maier
kontakt & impressum