Is it possible to issue compile error if object is stack created (including inherited types)?

You can require a token in the construction of A that is only passed in the body of 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>();
}

See it live

Tags:

C++

C++17

Factory