gpt4 book ai didi

c++ - 如何确保可变元组中的类型相同?

转载 作者:行者123 更新时间:2023-12-04 12:29:06 24 4
gpt4 key购买 nike

我想为具有特定类型(现在的算术类型)的可变数量的元组创建一个 toString 函数。
像这样的东西

<template T, typename enable_if<is_arithmetic_v<T>>::type* = nullptr>
toString(tuple<T...> tup)
{
std::stringstream ss;
std::apply([&ss](auto&&... args) {((ss << args << ";"), ...); }, tup);
return ss.str();
}
其中所有成员都是相同的类型,类型是数字类型。
我找到了 this ,但这允许所有类型和混合元组,如 make_tuple("str", 12.0f, 123) .
有人可以解释我如何在 C++17 中做到这一点吗?
谢谢 :)

最佳答案

您可以在 fold expression 的帮助下检查所有类型是否相同。 (自 C++17 起)。
例如。

template <typename T,                                                       // the 1st type 
typename... Args, // subsequent types
typename enable_if<is_arithmetic_v<T>>::type* = nullptr, // check for arithmetic type
typename enable_if<(is_same_v<T, Args> && ...)>::type* = nullptr> // check all the types are identical or not
auto toString(tuple<T, Args...> tup)
{
std::stringstream ss;
std::apply([&ss](auto&&... args) {((ss << args << ";"), ...); }, tup);
return ss.str();
}
LIVE

关于c++ - 如何确保可变元组中的类型相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67995709/

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