我有一个应用程序,其中 Base 是对象的工厂类,该对象应根据模板对以不同的方式创建。然而,只有非常特定(可数无限)数量的模板对才有意义。对于每一对合理的对,我都有一个(有时)模板化的派生工厂类。由于需要可行的正确选择模板对,因此使用 Base Factory 很容易出错。
我的问题是:如何阻止消费者直接使用 Base Factory?
template<typename T1, typename T2>
class Base{
Base()=delete;
public:
// many public static routines
T1 static foo(){ return 1; }
T2 static bar(){ return 2; }
};
template<typename T1>
class Derived: public Base<T1,float>{
// hopefully very little code, or none at all, as of now.
};
int main(){ // main is the consumer
Base<int,float>::foo(); // prevent
Derived<int> ::foo(); // permit
}
我希望编译器拒绝/抛出/错误 main 中带有注释“prevent”的行。我希望消费者不能直接访问 Base<..>::foo 和 Base<..>::bar ,除非通过 Derived<..> 访问。我曾希望
virtual
概念可以用于此目的;然而,它不会自然地从非静态转移到静态情况。
您可以创建
foo
方法 protected
,并通过 Derived
类使用 public
using
语句公开它:
template<typename T1, typename T2>
class Base {
Base() = delete;
protected:
// many public static routines
T1 static foo() { return 1; }
T2 static bar() { return 2; }
};
template<typename T1>
class Derived : public Base<T1, float> {
// hopefully very little code, or none at all, as of now.
public:
using Base<T1, float>::foo;
};
int main() { // main is the consumer
Base<int, float>::foo(); // prevent
Derived<int> ::foo(); // permit
}