基本上我希望通过工厂方法创建所有子类型(我有一个高大的域层次结构,有200多个类).
因为new,这不是问题,因为这可以在A(new私有)中被覆盖.
class A{
protected:
A();
public:
template<class T, typename... ARGUMENTS>
static T* create(ARGUMENTS&&... arguments);
};
class B : public A {
public:
B();
};
void test() {
B b;//compile error wanted here - but as a consequence of inheriting A
}
Run Code Online (Sandbox Code Playgroud)
这里A是"库/框架"类.而B是"用户创建的类".在B上要求typedef或类似可能没问题.
更新:我在A上添加了'create'函数,我打算用它来创建对象.
你可以在构造中要求一个令牌,A只在身体中传递A::create
#include <utility>
class A{
private:
struct create_token
{
create_token(const create_token &) = delete;
create_token& operator=(const create_token &) = delete;
create_token(create_token &&) = default;
create_token& operator=(create_token &&) = default;
};
protected:
A(create_token) {}
public:
template<class T, typename... ARGUMENTS>
static T* create(ARGUMENTS&&... arguments)
{
// Whatever creation mechanism here
return new T(create_token{}, std::forward<ARGUMENTS>(arguments)...);
}
};
class B : public A {
public:
template <typename Token> // Can't name A::create_token, it is private
B(Token tok) : A(std::move(tok)) {}
B(){} // Will always lack a `create_token`
};
int main() {
B b;//compile error wanted here - but as a consequence of inheriting A
B* b = A::create<B>();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
268 次 |
| 最近记录: |