Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning with automatic return type deduction: why do we need decltype when return defines the type anyway?

Tags:

c++

c++11

c++14

This is a question of what do do for the elementsSize() member function, regarding the automatic return type deduction:

#include <iostream>
#include <vector>

template<typename Element>
class ElementVector
{
    std::vector<Element> elementVec_;  

    // Other attributes.

    public: 

        ElementVector() = default; 

        ElementVector(const std::initializer_list<Element>& list)
            :
                elementVec_(list)
        {}

        auto elementsSize() // -> decltype(elementVec_size()) 
        {
            return elementVec_.size(); 
        }
};

using namespace std;

int main(int argc, const char *argv[])
{
    ElementVector<double> e = {1.2, 1.3, 1.4, 1.5};  

    cout << e.elementsSize() << endl;

    return 0;
}

The code above results in a compiler warning (gcc 4.8.2):

main.cpp:20:27: warning: ‘elementsSize’ function uses ‘auto’ type specifier without trailing return type [enabled by default]
         auto elementsSize() // -> decltype(elementVec_size()) 

I have read about the option of automatic return type deduction being made possible for C++14 without the use of decltype.

Writing the commented out decltype seems weird to me somehow. What am I doing wrong?

Note: I know that I could inherit from std::vector if there is no vector among "Other attributes", which is precisely the case in my actual problem.

like image 287
tmaric Avatar asked Jan 21 '14 12:01

tmaric


1 Answers

What am I doing wrong?

Nothing. GCC 4.8 implements auto-deduced return types, but as an enabled-by-default C++1y feature. Compiling with -std=c++1y will remove that warning.

[Answer converted from this comment.]

like image 51
2 revs Avatar answered Sep 28 '22 00:09

2 revs