|
|
Home » Community » Newbie corner » C++ templated class referencing each other
|
Re: C++ templated class referencing each other [message #55099 is a reply to message #55096] |
Sun, 11 October 2020 04:25 |
Lance
Messages: 633 Registered: March 2007
|
Contributor |
|
|
This hack seems to compiles in CLANG. I am sure there are smarter and more standard ways to serve your purpose.
Object.h
#ifndef _TestTemplate_Object_h_
#define _TestTemplate_Object_h_
#include "CompManager.h"
class Object{
public:
Object() : componentManager(*this){
}
void SayHello(){ componentManager.CreateComponent<int>(false,100); }
Object& GetObject(){ return *this;}
/*
Many public things
*/
private:
ComponentManager componentManager;
};
#include "CompManagerEx.h"
#endif
CompManager.h
class Object;
class ComponentManager{
public:
ComponentManager(Object& _object) : object(_object){}
template <class T> T& CreateComponent(bool active, int position);
/*
Many templated function that force me to write declaration in this .h file
*/
private:
Object& object;
};
CompManagerEx.h
template <class T> T&
ComponentManager::CreateComponent(bool active, int position)
{
static T t;
/*
Working code
*/
Object& obj=object.GetObject(); //This line is problematic
LOG("Hello inside ComponentManager::CreateComponent(bool active, int position)");
/*
Working code
*/
return t;
}
test.cpp
#include <Core/Core.h>
#include "Object.h"
using namespace Upp;
CONSOLE_APP_MAIN
{
Object obj;
obj.SayHello();
}
[Updated on: Sun, 11 October 2020 04:27] Report message to a moderator
|
|
|
Re: C++ templated class referencing each other [message #55100 is a reply to message #55096] |
Sun, 11 October 2020 04:36 |
Lance
Messages: 633 Registered: March 2007
|
Contributor |
|
|
Notice that I essentially put everything in the same header file (equivalently).
Also, if your can guarantee that ComponentManager Will be the first member variable (because why-not and you should put a static_assert to avoid accidently add some other member variable in front it subsequently), you can probably save the
member variable in the ComponentManager class. Simply define it like:
class Object;
class ComponentManager{
public:
ComponentManager(){}
template <class T> T& CreateComponent(bool active, int position);
/*
Many templated function that force me to write declaration in this .h file
*/
private:
Object& object(){
return *reinterpret_cast<Object*>(this);
}
};
And change other part of your code accordingly.
PS: If your Object class is virtual, some compiler might put vtable at this. In this case, above hack will be problematic. I will consider to let Object to privately inherit from ComponentManager.
[Updated on: Sun, 11 October 2020 04:45] Report message to a moderator
|
|
|
|
|
Goto Forum:
Current Time: Sat Dec 14 12:11:58 CET 2024
Total time taken to generate the page: 0.03418 seconds
|
|
|