如何将类型名称作为函数中的参数? (C++)
我需要能够传递类型名作为参数:
int X = FileRead(file, 9, char);
概念是 FileRead(std::fstream, int pos, ???) 读取 pos*sizeof(无论类型是什么)以获得所需的位置。 我尝试过模板:
template<typename T>
T FileRead(std::fstream file, int pos, T type)
{
T data;
file.read(reinterpret_cast<char*>(&data), sizeof(data));
return data;
}
但这要求我每次想使用 FileRead 时都创建一个要使用的类型的变量,而且我真的不想仅仅因为一个函数就重新设计整个程序,所以无论如何都可以使用类型名称作为参数?
I need to be able to pass a typename as a parameter:
int X = FileRead(file, 9, char);
The concept is for FileRead(std::fstream, int pos, ???) to read pos*sizeof(whatever the type is) to get the desired position. I tried templates:
template<typename T>
T FileRead(std::fstream file, int pos, T type)
{
T data;
file.read(reinterpret_cast<char*>(&data), sizeof(data));
return data;
}
but that required that I create a variable of the type to use every time I wanted to use FileRead, and I really don't feel like redesigning an entire program just because of one function, so is there anyway to use a typename as a parameter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要使用类型名称作为参数,请使用模板。
这假设该类型是默认可构造的。 如果不是,我想您无论如何都很难将其从文件中流出来。
像这样调用它:
如果您不想在调用中指定类型,您可以修改您的 API:
然后像这样调用它 - 推断类型:
To use the name of a type as a parameter, use a template.
This assumes that the type is default constructible. If it is not, I guess you would have difficulty streaming it out of a file anyway.
Call it like this:
If you do not want to have to specify the type in the call, you could modify your API:
Then call it like this - the type is inferred:
非常简单:
并通过以下方式调用它:
Very simple:
and call it via:
我知道这篇文章已得到解答,但我仍然遇到了问题,我从该页面的答案中找到了一种简单的方法。 您可以将类型名称传递给任何函数,如下所示:
I know this post is answered, but still, I had a problem with that and I found a simple way from this page answers. You can pass type name to any function like this:
一旦你的程序被编译,就不会有类型之类的东西了。 这就是C++的风格。
There is no such things as types once your program is compiled. This is the style of C++.