Home > OS >  Using a user-defined class as template type and using it's non-static data members for decision
Using a user-defined class as template type and using it's non-static data members for decision

Time:01-03

I have class like this :

class B{
public:
    const char* const getX() const {return X_;}
    const char* const getY() const {return Y_;}
    const char* const getZ() const {return Z_;}

protected:
    B(const char* const x, const char* const y, const char* const z) : 
                         X_(x), Y_(y), Z_(z) {}
private:
    const char *const X_ = nullptr;
    const char *const Y_ = nullptr;
    const char *const Z_ = nullptr;

};

class D : public B{
public:
      D() : B("X","Y","Z") {}
};

class D1 : public B{}; //Similar to D

Now, I want to use this class/classes as template for functions present in another class :

class S {

public:

template<class T>
int S1(some args);

};

template<class T>
int S::S1(some args) {
  //Do something based on template non-static member
  if(T::getX() == "X") //Getting error here -- illegal call of non-static member function 
  {}
}

Calling this function like below :

std::unique_ptr<S> s_ptr;
int rval = s_ptr->S1<D>();
  1. Is it possible to achieve this kind of functionality?
  2. Better way of doing things?

Please help!

Thank you.

CodePudding user response:

The idea here was not to go with non-static type but rather I could achieve this by using CRTP.

#include <string>

class Types {};

template <typename T>
class BaseTempl : public Types {
    public:
    static std::string A;
    static std::string B;
    static std::string C;
    static std::string D;
};


class Derived1 : public BaseTempl<Derived1> {
};

template <>
std::string BaseTempl<Derived1>::A = "A-Derived1";
template <>
std::string BaseTempl<Derived1>::B = "B-Derived1";
template <>
std::string BaseTempl<Derived1>::C = "C-Derived1";
template <>
std::string BaseTempl<Derived1>::D = "D-Derived1";

class Derived2 : public BaseTempl<Derived2> {
};

template <>
std::string BaseTempl<Derived2>::A = "A-Derived2";
template <>
std::string BaseTempl<Derived2>::B = "B-Derived2";
template <>
std::string BaseTempl<Derived2>::C = "C-Derived2";
template <>
std::string BaseTempl<Derived2>::D = "D-Derived2";

This allowed me to use polymorphic user-defined-class as template parameters and then use values inside these user-defined-template-type for some decision making.

  • Related