使用用户定义的 class 作为模板类型,并使用它的非静态数据成员进行决策。可能吗?

Using a user-defined class as template type and using it's non-static data members for decision making. Is it possible?

我有 class 这样的 :

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

现在,我想将此 class/classes 用作另一个 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 
  {}
}

像下面这样调用这个函数:

std::unique_ptr<S> s_ptr;
int rval = s_ptr->S1<D>();
  1. 是否可以实现这种功能?
  2. 更好的做事方式?

请帮忙!

谢谢。

这里的想法不是使用非静态类型,而是我可以通过使用 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";

这让我可以使用多态的用户定义的-class作为模板参数,然后使用这些用户定义的模板类型中的值进行某些决策。