C++基于函数名称动态创建函数的实现?
我有多个具有相似实现的功能。唯一的区别是他们调用不同的呼叫,基本上基于下面的函数名称。
// A.h
class A : public ParentA
{
public:
explicit A(B& b);
~A() override = default;
// accessors
C does_same_thing1() const;
C does_same_thing2() const;
C does_same_thing3() const;
// ...
}
// A.cpp
C A::does_same_thing1() const
{
...
return xyz.values().thing1();
}
C A::does_same_thing2() const
{
...
return xyz.values().thing2();
}
C A::does_same_thing3() const
{
...
return xyz.values().thing3();
}
我想知道是否有一种动态填写几乎相同的功能的方法,除了他们称之为的登录器(thing1(),thing2()和thing 3(),这实际上不止一次发生,而不仅仅是在返回行上)基于其功能名称。在C ++中可以吗?
谢谢!
I have multiple functions that have long and similar implementations. The only difference is they call different calls, which is basically based on the function name like below.
// A.h
class A : public ParentA
{
public:
explicit A(B& b);
~A() override = default;
// accessors
C does_same_thing1() const;
C does_same_thing2() const;
C does_same_thing3() const;
// ...
}
// A.cpp
C A::does_same_thing1() const
{
...
return xyz.values().thing1();
}
C A::does_same_thing2() const
{
...
return xyz.values().thing2();
}
C A::does_same_thing3() const
{
...
return xyz.values().thing3();
}
I wonder if there's a way to dynamically fill out the functions that are almost the same except the accessors they call (thing1(), thing2(), and thing3(), and this actually happens more than once, not just on the return line) based on their function names. Would this be possible in C++?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以编写一个功能模板,然后让呼叫者选择要返回的内容:
详细信息取决于您从问题中遗漏的详细信息。例如,
xyz.values()
的类型是否可供呼叫者使用?另外,您必须让呼叫者选择f
或编写包装器:You can write one function template and let the caller choose what is to be returned:
Details depend on details you left out from the question. For example, is the type of
xyz.values()
available to the caller? Also, it is up to you to let the caller pickf
or write wrappers:一些选项是:
创建基类
创建一个覆盖类创建
不同的覆盖类示例,您也可以在此处查看lambda示例
使用
Some options are:
Create your base class
Create an overriding class
Create a different overriding class
Example on use, you can see the Lambda example here too