gpt4 book ai didi

c++ - 为不同的文件扩展名调用不同的函数

转载 作者:行者123 更新时间:2023-11-28 06:48:26 26 4
gpt4 key购买 nike

情况是这样的:

我有一个用 C++ 编写的图形类,我需要从文件构建图形对象。问题是 Graph 以多种不同的方式存储在文件中,所以我在考虑一个函数,使用文件扩展名,可以调用正确的过程来构建特定格式的 Graph。我该如何进行?我是不是错了,或者我不能在类里面重载运算符>>?提前致谢。

最佳答案

operator>>(应该)不知道它从中提取的流的任何细节,因此使用此运算符可能是错误的策略。

最好的方法是:

graph_type load_from_file(const std::string& file_path) { //or use something like boost::filesystem::path

std::ofstream file { file_path };

if(endswith(file_path, ".graph") {
return deserialize_from_graph(ofstream);
}
if(endswith(file_path, ".g2") {
return deserialize_from_g2(ofstream);
}
//other formats here


//else throw
}

注意,endswith 不是来自标准库,但是 boost 在它的字符串算法中有一个实现。

关于c++ - 为不同的文件扩展名调用不同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24494338/

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