2

I have a class with data members.

class Sph
{
public:
    Sph( float radius , float segments , const Shader& shader );
    Sph(const Sph& geometry);
    Sph& operator = (const Sph& geometry);
    ~Sph();
    void init();
    void CleanUp();
    void draw();
    void CreateUI(QFormLayout* layout);
    std::vector< Sum_Vertices > GetVertices();

private:
    float Radius,Segments;
    bool isInited;
    unsigned int m_VAO, m_VBO , m_IBO;
    int iNumsToDraw;
    bool isChanged;
    Shader shader;
    int indexCount;
};

in order to change the data of the class I have to write individual methods.

void SetRadius( float radius )
{
   this->Radius = radius;
}

Is it possible to write a templated function which can change different data members of the class?

iammilind
  • 68,093
  • 33
  • 169
  • 336

2 Answers2

1

Since the variables are different by names, the template may not help here.


This is a classic case, where you can use macros to your advantage & ease.

Definition:

#define GET_SET(X) X; \ 
    public: const decltype(X)& get_##X() const { return X; } \ 
            void set_##X(const decltype(X)& value) { X = value; } private:

Utility:

class Sph
{
   ...
private:
  float GET_SET(Radius);
  float GET_SET(Segments);
  ...
};

Usage:

Sph sph;
sph.set_Radius(3.3);
cout << sph.get_Radius() << "\n";

Demo.

iammilind
  • 68,093
  • 33
  • 169
  • 336
-1
class Sph {
  /* ... */
public:
  template<typename ParamType, typename... Extras> void SetParam(ParamType, Extras...);
  /* ... */
};

template<> inline void Sph::SetParam(float radius) {
  Radius = radius;
}

template<> inline void Sph::SetParam(float segments,
    bool ignored_dummy_argument_to_distinguish_between_two_overloads)
{
  Segments = segments;
}

template<> inline void Sph::SetParam(bool inited) {
  isInited = inited;
}
bipll
  • 11,747
  • 1
  • 18
  • 32
  • 2
    if i have more than two overloads how do i handle that situation. –  Sep 07 '19 at 03:48