gpt4 book ai didi

c++ - c++自动生成函数签名

转载 作者:太空宇宙 更新时间:2023-11-04 12:39:15 26 4
gpt4 key购买 nike

我在生成函数方面遇到了问题,它变得非常乏味,复制和粘贴我有大约 400 个函数。自动生成它们的最简单方法是什么?
我希望只输入 IController.h,其余的会自动填充,如果有人能指导我做这样的事情,那就太好了。

我有 4 个单独的文件。

IController.h
Controller.h
Controller.cpp
MockController.h

例如,在 IController.h 文件中,我有一个名为 display 的函数

class IController
{
public:
virtual void display(Gui* gui) = 0;
}

Controller 类将从 IController 继承,关键字 virtual 被移除,=0。

class Controller : public IController
{
public:
void display(Gui* gui);
}

Controller.cpp 将包含定义

void Controller::display(Gui* gui)
{

}

最后 MockController.h 将包含以下内容

class MockController : public IController
{
public:
MOCK_METHOD1(display, void(Gui* gui));
};

最佳答案

我花了几天时间才弄明白,希望这对我设法使用下面显示的脚本解决上述问题的人有所帮助。 gmock_gen.py 目前不适用于 python 3.7.2,我安装了 2.7.13,下面的脚本可以工作。

用户只需要为第一个接口(interface)类生成代码,所有其他文件都是自动生成的。

import os

#read contents of IController.h
filename = "IController.h"
file = open(filename,"r")

#variables
flag = False
classheader = ""
mockheader = ""
classbody = None
header = []
classitems = []

#read each line in the file
for line in file:
# if the class name has been found
if(filename[:-2] in line):
flag = True
# save all data before the calss name
if flag == False:
header.append(line)
#
if filename[:-2] in line:
flag = True
classname = filename[1:-2]
line = line.replace("class ", "public ")
classbody = "class " + classname + " : " + line

# remove virtual = 0
if "virtual" in line:
line = line.replace("virtual","")
line = line.replace(" = 0","")
classitems.append(line)

classbody += "\n"
classbody += "{\n"
classbody += " public:\n"

for x in classitems:
classbody += x
classbody + "\n"

classbody += "};"

for x in header:
classheader += x

classheader += "#include " + "\"" + filename + "\"" + "\n\n"
mockheader += classheader
classheader += classbody

#create controller.h file
f = open(filename[1:], "w")
f.write(classheader)

cppbody = ""

for x in classitems:
temp = x.split(" ", 2)
temp2 = temp[1] + " " + filename[1:-2] + "::" + temp[2].replace(";","{\n\n\n}\n")
cppbody += temp2

#create controller.cpp file
cppfilename = filename[1:-2] + ".cpp"
f = open(cppfilename,"w")
f.write(mockheader)
f.write(cppbody)


mocktemp = "Temp" + filename[1:]
mockfilename = "Mock" + filename[1:]

input = "python gmock_gen.py " + filename
os.system(input + " > " + mocktemp)

#create MockIController.h
with open(mocktemp) as f:
with open(mockfilename, "w") as f1:
f1.write(mockheader)
for line in f:
f1.write(line)

关于c++ - c++自动生成函数签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55059531/

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