gpt4 book ai didi

c++ - 脚本库和函数模板

转载 作者:太空宇宙 更新时间:2023-11-04 11:27:23 25 4
gpt4 key购买 nike

上下文

我目前正在开发自己的库,用于在 C++ 应用程序中加载自定义脚本。下面是一些示例代码,用于解释它在做什么:

  1. 脚本部分:

测试.ctv

script
{
object player = access("player");
player.posX = 1 + 2;
access("map").load("map.txt");
}
  1. C++ 部分:

测试.cpp

class Player : public Loadable{
private:
friend class cTVScript::scriptExecutor;
primaryLoadable<int> posX;
stringLoadable name;
public:
Player() : Loadable(&posX, "posX", &name, "name");
}

class Map : public Loadable{
private:
friend class cTVScript::scriptExecutor;
std::string mapName;

public:
void load(std::string map) {
mapName = map;
}
Map() : Loadable(&load, "load") {}
}

int main() {
Player *p = new Player();
Map *m = new Map();
cTVScript::LoadScript("test.ctv");
cTVScript::AddObject(p, "player");
cTVScript::AddObject(m, "map");
std::cout << player.posX.get() << std::endl; // for example purpose we just assume that posX are public
std::cout << player.mapName.get() << std::endl; // same for mapName
}

问题

cTVScript::scriptExecutor 访问和使用变量非常简单,但我的主要问题在别处:

  • 在 C++ 中,如何保存和调用具有不同原型(prototype)的方法/函数?
  • 编译器的一些技巧可以使它更容易吗? (比如知道参数的类型和数量?)

当前的解决方法

让用户定义一个子函数,如AccessibleLoad:

class Map{
[...]
public:
void load(std::string map) {
mapName = map;
}
static void AccessibleLoad(cTVScript::CallingPack& pack) {
/* arguments */
std::string map;
pack.loadArguments(map); // here the user ask for each arguments

/*calling object */
Map* _this;
pack.loadCallingObject(_this); // and here he ask for the calling object

_this->load(map);
}
Map() : Loadable(&AccessibleLoad, "load") {}
}

那么!

有什么技巧或方法可以让我更轻松地在我的库中使用函数/方法吗? (比如用编译器构造这些函数?(不这么认为但最好问))

编辑

有消息了!我有自己的答案,我会发布它(但它有点长)(顺便说一句,英语不是我的母语,所以如果我犯了错误,请告诉我,我会编辑)

最佳答案

执行 C++ -> 您的脚本调用。顺便说一下,这是 c++11

您将需要某种形式的打包器,它可以获取类型并将其添加进去。

class SomeClassYouCanCallAScriptFunction {
// the order of these templates matter or else
// the one bellow will not be able to find the one higher

template<class T, class... Args>
callFunction(string name){
// run your code to call your scripted function
// arguments has the arguments array
}

template<class T, class... Args>
callFunction(string name, T var){
// last one
// either this
arguments.pack<T>(var);
// or this
arguments.pack(to_string(var));
// or the like
// now do the next one
callFunction(name);
}



template<class T, class... Args>
callFunction(string name, T var, Args... args){
// either this
arguments.pack<T>(var);
// or this
arguments.pack(to_string(var));
// or the like
// now do the next one
callFunction(name, args...);
}







}


someClass.callFunction("scriptFunc", "ya", 42, someVectMaybe);

最好的办法就是提供一个 arguments变量并让用户获得传入的参数,如 arguments.get<T>(index)

关于c++ - 脚本库和函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26158643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com