gpt4 book ai didi

c++ - C++ 17的可选和可变排序函数参数

转载 作者:行者123 更新时间:2023-12-01 14:44:19 30 4
gpt4 key购买 nike

我正在尝试改善串行端口类的构造函数。目前,有很多重载可以处理不同的情况(端口,波特率,数据位,奇偶校验,创建时打开,回调等)。为了允许此类用户仅以任意顺序传递他/她需要的参数,我开始如下:

#include <iostream>
#include <string>
#include <tuple>

template <typename T, typename Tuple>
struct has_type;

template <typename T, typename... Us>
struct has_type<T, std::tuple<Us...>> : std::disjunction<std::is_same<T, Us>...> {};

template <typename ...UnorderedArgs>
std::string getPort(std::tuple<UnorderedArgs...> arg_set)
{
if constexpr (has_type<std::string, std::tuple<UnorderedArgs...>>::value)
return std::get<std::string &&>(std::move(arg_set));
else
return "NotSet";
}

class SerialPort
{
public:
template <typename... Args>
SerialPort(Args ...args) :
SerialPort(std::forward_as_tuple(std::move(args)...))
{}

template <typename ...UnorderedArgs>
SerialPort(std::tuple<UnorderedArgs...> arg_set) :
SerialPort(getPort(std::move(arg_set)))
{}

SerialPort(const std::string &port) // [X]
{
std::cout << "SerialPort " << port << std::endl;
}
};

int main()
{
std::string port = "/dev/tty";
SerialPort sp(1, port); // without 1 the compiler would use [X]
return 0;
}

此代码将端口设置为 NotSet,因此带有 if constexpr的部件无法正常工作。如何解决?

最佳答案

This code sets the port to NotSet, so the part with if constexpr is not working as intended. How can this be fixed?



如果引用,则存在问题:当您检查 std::string中是否存在 has_type时,存在 std::string但带有引用(如果我没错,则由 &&给出 std::move())。

解决方案:删除引用
template <typename T, typename... Us>
struct has_type<T, std::tuple<Us...>>
: std::disjunction<std::is_same<T, std::remove_reference_t<Us>>...> {};
// ..................................^^^^^^^^^^^^^^^^^^^^^^^^^^^

-编辑-

正如Jarod42指出的(谢谢!),这种方式 has_type不再正确。

也许您需要一个 has_type来检测类型的存在并检查引用...

也许最好保留原始 has_type并使用 std::remove_reference_t调用它
// ............................................VVVVVVVVVVVVVVVVVVVVVVV
if constexpr (has_type<std::string, std::tuple<std::remove_reference_t<UnorderedArgs>...>>::value)
return std::get<std::string &&>(std::move(arg_set));
else
return "NotSet";

关于c++ - C++ 17的可选和可变排序函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58541274/

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