我有這樣的課:
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 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>();
- 有沒有可能實作這種功能?
- 更好的做事方式?
請幫忙!
謝謝你。
uj5u.com熱心網友回復:
這里的想法不是使用非靜態型別,而是我可以通過使用 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";
這允許我使用多型用戶定義類作為模板引數,然后使用這些用戶定義模板型別中的值進行某些決策。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/402185.html
上一篇:查找是否可以使用一組引數實體化類模板,arity-wise(在C 17中)
下一篇:SFINAE歧義
