递归尾随返回类型?

时间:2011-11-05 21:12:14

标签: c++ c++11 decltype

  

可能重复:
  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 ...)

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:0)

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

#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