【问题标题】:operate on c++ 11 variadic template parameters, store into tuple对 c++ 11 可变参数模板参数进行操作,存储到元组中
【发布时间】:2018-02-20 06:47:44
【问题描述】:

我正在尝试学习一些带有可变参数模板参数的 c++ 11。

我想将浮点输入参数列表传递给 convertTest(),然后返回一个 std::tuple 整数。我尝试在 g++ 中编译以下内容:

template<typename ...ArgsIn, typename ...ArgsOut>
static inline std::tuple<ArgsOut...> convertTest(float nextArg, ArgsIn... remainingArgs)
{
    auto a = convertTest(remainingArgs...);
    auto b = std::make_tuple(int(nextArg));
    auto c = std::tuple_cat(a, b);

    return c;
}

static inline std::tuple<int> convertTest(float lastArgIn)
{
    return std::make_tuple((int)lastArgIn);
}

int main()
{
    auto res = convertTest(0.5f, 10.11f);
    return 0;
}

我收到以下错误:

 error: conversion from 'std::tuple<int, int>' to non-scalar type 'std::tuple<>' requested

我不确定为什么返回类型 std::tuple&lt;ArgsOut...&gt; 会解析为 std::tuple&lt;&gt;。有什么想法吗?

我尝试将返回类型设为 auto,但我收到了关于在这种情况下缺少尾随返回类型的投诉。

有什么想法吗?

【问题讨论】:

  • “我已经尝试将返回类型设为 auto,因为 C++11 需要尾随返回类型(即 auto foo() -&gt; returnType {/*...*/})。 C++14 允许使用简单的auto foo() {/*...*/} 来推断返回类型。

标签: c++ c++11 templates variadic


【解决方案1】:

Argout是不可演绎的,所以变成空列表。 因此,您必须改为按该顺序编写函数

template<typename ... ArgsOut, typename ...ArgsIn>
static std::tuple<ArgsOut...> convertTest(float nextArg, ArgsIn... remainingArgs);

然后叫它

convertTest<int, int>(0.5f, 10.11f);

顺便说一句,你可以简单地写成这样(消除你只接受float的事实)

template<typename ...Args>
auto convertTest(Args... args)
-> decltype(std::make_tuple(static_cast<int>(args)...))
{
    return std::make_tuple(static_cast<int>(args)...)
}

【讨论】:

  • 感谢您的反馈!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-29
  • 2017-07-11
  • 1970-01-01
  • 2021-06-04
相关资源
最近更新 更多