【问题标题】:Recursive trailing return type? [duplicate]递归尾随返回类型? [复制]
【发布时间】:2011-11-05 21:12:13
【问题描述】:

可能重复:
trailing return type using decltype with a variadic template function

我想创建一个汇总多个值的函数。如果我不使用尾随返回类型,那么count() 使用第一个参数的类型作为它的返回类型。但是,当使用尾随返回类型时,我无法编译代码:

#include <iostream>

template<typename T>
inline T sum(T a) {
  return a;
}

template<typename T, typename... Args>
inline auto sum(T a, Args... b) -> decltype(a + sum(b...)) {
  return (a + sum(b...));
}

int main() {
  std::cout << sum(1, 2.5f, 3, 4);
  return 0;
}

错误(GCC)是:

main.cpp: In function ‘int main()’:
main.cpp:16:30: error: no matching function for call to ‘sum(int, float, int, int)’
main.cpp:16:30: note: candidates are:
main.cpp:5:10: note: template<class T> T sum(T)
main.cpp:10:13: note: template<class T, class ... Args> decltype ((a + sum(sum::b ...))) sum(T, Args ...)

我怎样才能让它工作?

【问题讨论】:

  • count不应该是sum吗?
  • 有问题的第 16 行的 int main() 在哪里? sscce.org
  • 在这里工作:ideone.com/v8nJK
  • @jpalecek:它适用于 2 个参数,但不适用于 3 个或更多参数:ideone.com/CYCZE
  • @JakubWieczorek 它似乎确实是一个完全相同的副本。我会标记关闭。

标签: c++ c++11 decltype


【解决方案1】:

它不漂亮,但我使用模板结构让它工作:

#include <iostream>

template<typename... Args>
struct sum_helper;

template<typename T>
struct sum_helper<T> {
  typedef T sum_type;
};

template<typename T, typename... Args>
struct sum_helper<T, Args...> {
  typedef decltype(*(T*)0 + *(typename sum_helper<Args...>::sum_type*)0) sum_type;
};

template<typename T>
inline T sum(T a) {
  return a;
}

template<typename T, typename... Args>
inline typename sum_helper<T, Args...>::sum_type sum(T a, Args... b) {
  return a + sum(b...);
}

int main()
{
  std::cout << sum(1, 2, 3) << " "
        << sum(1, 1.1, 1.11) << std::endl;
  return 0;
}

http://ideone.com/7wYXf

【讨论】:

    猜你喜欢
    • 2018-04-22
    • 1970-01-01
    • 2015-09-10
    • 2018-05-12
    • 2019-07-06
    • 2015-12-21
    • 2011-11-07
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多