Recursive trailing return type?
Possible Duplicate:
trailing return type using decltype with a variadic template function
I want to make a function that sums up several values. If I don't use a trailing return type then count()
uses the type of the first argument as it's return type. However, when using a trailing return type I am not able to get the code to compile:
#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;
}
The error (GCC) is:
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 ...)
How can I get this to work?
It's not pretty, but I got it working using a template struct:
#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
链接地址: http://www.djcxy.com/p/66498.html上一篇: 使用decltype(var)后跟内部类型“var”的C ++ 11编译器错误
下一篇: 递归追溯返回类型?