特定元组元素的总和
Sum of specific tuple elements
我正在尝试计算元组特定元素的总和,但无法编译。
这是我要编写的函数的样子:
template <int ...ids>
float sum(std::tuple<int, int, std::string, float> things)
{
return "<sum of elements of ids>";
}
我想这样称呼它:
std::tuple<int, int, std::string, float> my_things= { 1, 2, "3", 4.0f };
float sum_numbers = sum<0, 1, 3>(my_things);
我无法使用折叠来让它工作。 :/这甚至可能吗?如果是,怎么会?
提前致谢!
I couldn't get it to work using folding. :/ Is this even possible? If yes, how so?
下面呢?
template <int ...ids>
float sum (std::tuple<int, int, std::string, float> things)
{
return ( 0.0f + ... + std::get<ids>(things) );
}
但我建议 (1) 更通用,(2) 使用 std::size_t
作为索引
template <std::size_t ... Ids, template T>
auto sum (T const & things)
{ return ( 0 + ... + std::get<Ids>(things) ); }
我正在尝试计算元组特定元素的总和,但无法编译。
这是我要编写的函数的样子:
template <int ...ids>
float sum(std::tuple<int, int, std::string, float> things)
{
return "<sum of elements of ids>";
}
我想这样称呼它:
std::tuple<int, int, std::string, float> my_things= { 1, 2, "3", 4.0f };
float sum_numbers = sum<0, 1, 3>(my_things);
我无法使用折叠来让它工作。 :/这甚至可能吗?如果是,怎么会?
提前致谢!
I couldn't get it to work using folding. :/ Is this even possible? If yes, how so?
下面呢?
template <int ...ids>
float sum (std::tuple<int, int, std::string, float> things)
{
return ( 0.0f + ... + std::get<ids>(things) );
}
但我建议 (1) 更通用,(2) 使用 std::size_t
作为索引
template <std::size_t ... Ids, template T>
auto sum (T const & things)
{ return ( 0 + ... + std::get<Ids>(things) ); }