gpt4 book ai didi

c++ - 拆包和使用自动时重用变量

转载 作者:行者123 更新时间:2023-12-03 07:15:45 31 4
gpt4 key购买 nike

我正在编写一个用于将代码从Go转换为C++ 20(go2cpp)的小程序。大部分代码转换起来相对简单,但是我只限于一种特殊情况,即在拆开元组时会发生名称冲突。
这是一个可以另存为ie的完整示例。 main.cpp:

#include <cstdlib>
#include <iostream>
#include <string>
#include <optional>
#include <tuple>

using namespace std::string_literals;
using error = std::optional<std::string>;

// convert a string to a double
// return both the double and an error (optional string)
// this must behave in a simiar fashion to strconv.ParseFloat in Go
auto strconvParseFloat(std::string s, int n) -> std::tuple<double, error>
{
// n is ignored, for now
try {
return std::tuple { std::stod(s), std::nullopt };
} catch (const std::invalid_argument& ia) {
return std::tuple { 0.0, std::optional { "invalid argument"s } };
}
}

// convert a string to an int
// return both the int and an error (optional string)
// this must behave in a simiar fashion to strconv.ParseInt in Go
auto strconvParseInt(std::string, int a, int n) -> std::tuple<int, error>
{
return std::tuple { 0, std::optional { "not implemented"s } };
}

auto isNum(std::string s) -> bool
{
auto [_0, err] = strconvParseFloat(s, 64);
auto isFloat = (err == std::nullopt);
auto [_1, err] = strconvParseInt(s, 0, 64);
auto isInt = (err == std::nullopt);
return isFloat || isInt;
}

auto main(int argc, char** argv) -> int
{
const auto s = "3.14"s;
//const auto s = "asdf"s;
std::cout << s << " is a number: "s << std::boolalpha << isNum(s) << std::endl;
return EXIT_SUCCESS;
}

我使用以下命令在GCC 10.2.0中进行编译:
g++ -o main -std=c++2a -O2 -pipe -fPIC -fno-plt -fstack-protector-strong -Wall -Wshadow -Wpedantic -Wno-parentheses -Wfatal-errors -Wvla main.cpp
我收到的错误消息是这样的:
main.cpp: In function ‘bool isNum(std::string)’:
main.cpp:36:15: error: conflicting declaration ‘auto err’
36 | auto [_1, err] = strconvParseInt(s, 0, 64);
| ^~~
如果我将第一个 err重命名为 err1,第二个 err重命名为 err2,则该程序将编译并正常运行。
如何强制或说服C++编译器相信 err中第二次使用 auto [_1, err]是可以的(就像在Go中将如何使用),并且我想重新声明 err?是否有我可以使用的编译器指令,或者以某种方式将 std::tiestd::ignore结合使用?
我怀疑在这种情况下我必须使用 namespace ,但是在自动从Go转换代码时,宁愿寻找另一种方法,该方法不涉及必须跟踪进入该块的内容。

最佳答案

是的,确实可以在第二个调用中使用std::tiestd::ignore,如下所示:

std::tie(std::ignore, err) = strconvParseInt(s, 0, 64);
这是唯一需要的更改,您无需对 namespace做任何事情。
这是 demo

关于c++ - 拆包和使用自动时重用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64372269/

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