c++ - 递归尾随返回类型?

标签 c++ c++11 decltype

<分区>

Possible Duplicate:
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 ...)

我怎样才能让它工作?

最佳答案

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

#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

关于c++ - 递归尾随返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8023332/

相关文章:

c++ - QThreads之间如何发送数据?

c++ - 无法获取 std::mutex 来正确保护线程访问

c++ - 基于对 vector 中第一个元素的降序排序没有给出期望的结果

c++ - 无法使 decltype 说明符在 lambda 函数内正常工作

c++ - CRTP:如何推断用作返回类型的成员类型?

c++ - 在模板中隐式获取字符串的长度

c++ - 发送批量消息时 BOOST::async_wait 错误

c++ - 当 lambda 作为参数传入时推导模板参数

c++ - 在编译时测试字节序 : is this constexpr function correct according to the standard?

c++ - 你能在对象函数上用 decltype 声明一个成员变量吗?