1

I wrote this answer. Why this code doesn't compiles under g++ while it compiles under VC++?
How can I make the code portable?

My code:

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

template<typename T, typename... Ts>
inline auto sum(T t, Ts... ts)->decltype(t+sum(ts...)){
    return t+sum(ts...);
}

#include<iostream>
int main(){
    std::cout<<sum(2.5, 2)<<'\n'            //works
             <<sum(2, 2.5)<<'\n';           //works
    std::cout<<sum(1u, 2.5, 3.f, '0')<<'\n';//doesn't work, don't know why
}

See it in online compiler under g++
See it in online compiler under MSVC++

Community
  • 1
  • 1
GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52
  • The variadic version of `sum` isn't in scope until its declarator is complete, so you can't use it in the trailing return type (which is part of the declarator). – T.C. Sep 14 '14 at 11:32
  • @T.C. What you suggest me to do to make the code correct? – GingerPlusPlus Sep 14 '14 at 11:39
  • 1
    @GingerPlusPlus In C++14, simply use return type deduction. In C++11, http://stackoverflow.com/questions/3744400/trailing-return-type-using-decltype-with-a-variadic-template-function. – T.C. Sep 14 '14 at 11:46

0 Answers0