简体   繁体   中英

C++ Template function differences between VC++ and g++/Xcode

I am currently powering through a C++ course on Pluralsight and I am having some trouble figuring out why a template function example is working on VS Community 2013 using the MS compiler, but not on my preferred IDE of CLion 1.2 using g++ on Ubuntu 15.04. I have also tried on OSX10.10/CLion 1.2/Xcode compiler with the same errors. (Note: the CLion cmake is set to "-std=c++11")

The simple function takes a STL array of an unknown number of elements and returns the sum of all the elements.

The code is:

#include<array>
#include<iostream>
using namespace std;

template<int n>
int sum(array<int, n> values)
{
 int result = 0;
 for (auto value : values)
 {
  result += value;
 }
 return result;
}

int main()
{
    array<int,5> numbers = {{1,2,3,4,5}};
    array<int,3> more_numbers = {{1,3,5}};

    cout << sum(numbers) << endl;
    cout << sum(more_numbers) << endl;

    getchar();
    return 0;
}

In VS 2013 this works fine and outputs the expected:

15
9

However on both the Ubuntu and OSX CLion IDE's the following errors are shown for lines 22 and 23 (the two sum function calls):

error: no matching function for call to 'sum'

accompanied by a debugger note:

note: candidate template ignored: substitution failure : deduced non-type template argument does not have the same type as the its(sic) corresponding template parameter ('unsigned long' vs 'int')
int sum(arrayvalues)
^

Note really understanding, the first thing I tried was using a typename parameter for the template too:

template<typename T, T n>
T sum(array<T, n> values)
{
 int result = 0;
 for (auto value : values)
 {
  result += value;
 }
 return result;
}

and calling it with:

cout << sum<int>(numbers) << endl;

But this produced the same errors upon compiling. Was I wrong to try this/am I heading in the wrong direction or was this a valid attempt at fixing the problem?

I am obviously aware that there are differences between how the compilers do things, however would anybody be able to tell me why I'm experiencing the error in CLion, and also let me know the correct course of action for achieving the desired result?

Many Thanks, any advice would be greatly appreciated.

The non-type template argument for std::array should be a std::size_t , not an int .

template<std::size_t n>
//       ^^^^^^^^^^^
int sum(array<int, n> values)
{
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM