C++:使用传入的字符串参数来访问类型中的某些内容
我的目标是访问作为 myFunction 内部参数传入的类。
这就是我想要做的:
void myFunction(string myString)
{
callFunctionOn(OuterType::InnerType::myString);
}
我试图对类型中的某些东西调用一些函数。例如,我在其他文件中的代码可能如下所示:
namespace OuterType {
namespace InnerType {
//stuff here
}
}
但是,以这种方式使用 myString 不起作用。如果 myString 保存值“class1”,那么我希望 callFunctionOn 部分被解释,因为
callFunctionOn(OuterType::InnerType::class1);
我觉得这非常简单,但我一整天都在编程,我的头脑变得疲倦......
已解决:它看起来像顺序为此,我需要一种带有反思的语言。为了解决这个问题,我采取了不同的方法来解决这个问题,并传递了一个指向该类的指针。
My goal is to access a class that is passed in as a parameter inside of myFunction.
Here's what I'm trying to do:
void myFunction(string myString)
{
callFunctionOn(OuterType::InnerType::myString);
}
I'm trying to call some function on something that's in a type. For example, my code in some other file might look like:
namespace OuterType {
namespace InnerType {
//stuff here
}
}
However, using myString in that way doesn't work. If myString holds the value "class1", then I want that callFunctionOn part to be interpreted as
callFunctionOn(OuterType::InnerType::class1);
I feel like this is super simple, but I've been programming all day and my mind grows tired...
SOLVED: It looks like in order to this in this way, I'd need a language with reflection. To solve this I took a different approach to the problem and passed in a pointer to the class instead.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C++ 没有内置反射,但它有指向数据、函数和类成员的指针。因此,您可以使用 std::map 或 unordered_set 来查找具有特定名称的指针(您必须事先将所有名称/指针对添加到映射中)。
您的解决方案可能类似于:
当然,指针的类型可能需要更改以满足您的应用程序要求。
C++ doesn't have reflection built in, but it does have pointers to data, functions, and class members. So you can use a
std::map
orunordered_set
to find the pointer with a particular name (you have to add all the name/pointer pairs into the map beforehand).Your solution is likely to look something like:
Of course the type of the pointer will probably need to change to meet your application requirements.
您正在尝试基于包含变量名称的运行时字符串来访问变量?那是不可能的;编译和链接后变量名称消失。 (除非它们被保留以方便调试)。
You're trying to access a variable based on a run-time string that contains its name? That's not possible; the names of variables disappear after compilation and linking. (Except insofar as they are kept around to facilitate debugging).
您的意思是:
Do you mean :
也许这个想法:operator() 可以接受参数,将其包装在一个类中,ine 可以根据其参数进行在重载的operator() 中解析的调用。
您需要构建运行时字符串值的映射作为实例方法的键和指针,如上所示。我用它来重新调度跟踪和自定义运行时调度,开销小于 RTTI。
如果没有找到密钥,这允许您使用默认值或您希望的其他逻辑。
maybe this idea: operator() can take parameters, wrapping it in a class ine can make calls that are resolved in the overloaded operator() based on its parameters.
you need to build a map of runtime string values as keys and pointers to instance methods as seen above. i used this for re-dispatch tracing and custom runtime dispatch with lesser than RTTI overhead.
this allows you to have default, if no key found, or other logic as you wish.