模板化的部分应用程序调用问题

Templated partial application call issues

本文关键字:应用程序 调用 问题      更新时间:2023-10-16

对于一月份即将推出的Coursework,我开始开发一个小型DirectX引擎。为了了解性能是否有所提高,我想尽量不使用任何虚拟机(我知道虚拟机并不全是坏的,但我只是想看看没有它们是否可行)。

当我开始使用简单的StateManager时,很难避免虚拟化,但这是我目前的方法:

#include <boostfunction.hpp>
#include <boostbind.hpp>
template <class Derived>
struct TBaseState {
bool update(float delta) {
return static_cast<Derived *>(this)->update(delta);
};
};
struct CTestState : TBaseState<CTestState> {
bool update(float delta) {
return true;
}
};
class StateManager
{
public:
template <class StateClass> static void setState(StateClass nextState)
{
m_funcptrUpdate = boost::bind(&TBaseState<StateClass>::update,     boost::ref(nextState), _1);
}
static bool update(float delta) 
{
return m_funcptrUpdate(delta);
}
protected:
private:
static boost::function<bool (float)> m_funcptrUpdate;
};

Visual Studio 2010的Intellisense似乎认为一切都很好,但当我想用一种非常基本的方法编译程序并测试StateManager时:

CTestState* t = new CTestState(); 
StateManager::setState(*t);
StateManager::update(0.0f);

在链接阶段引发以下错误:

error LNK2001: unresolved external symbol "private: static class boost::function<bool __cdecl(float)> StateManager::m_funcptrUpdate" (?m_funcptrUpdate@StateManager@@0V?$function@$$A6A_NM@Z@boost@@A)

很明显,他找不到绑定函数,但我该如何解决这个问题?如果我使用boost::直接绑定到某个类,我会得到类似的错误。由于我是一名计算机科学专业的学生,我也会对一些没有提升的见解或方法感兴趣(例如bind1st,…)

编辑:我也在考虑使用C++11可变模板,但课程要求之一是坚持使用VS2012。

需要为静态类成员提供存储空间。它们就像extern变量。将定义添加到类定义之外的.cpp文件中:

boost::function<bool (float)> StateManager::m_funcptrUpdate;

此外,在此代码中:

template <class StateClass> static void setState(StateClass nextState)
{
m_funcptrUpdate = boost::bind(&TBaseState<StateClass>::update,
boost::ref(nextState), _1);
}

您正在维护存储对本地变量nextState的引用。setState返回后,该引用将无效。