What the C ++ 14 standard says about cars as an argument type

Let's look at the following code below:

#include <iostream>

class Test
{
private:
    int x;
public:
    Test(int _x) :
        x(_x)
    {
        std::cout << "Im being constructed" << std::endl;
    }

    int getx()
    {
        return this->x;
    }

    friend std::ostream& operator<<(std::ostream& os, Test& other)
    {
        os << other.getx();
        return os;
    }
};

auto func(auto x)
{
    std::cout << x << std::endl;
    return x.getx();
}

int main()
{
    auto y = func(20);

    return 0;
}

How does the compiler decide if (20) should be an int or Test object? The constructor for the test is not explicit, so what does the standard say about this?

+4
source share
2 answers

So, although gcc allows auto as a parameter in functions, this is not part of C ++ 14, but part of concept-lite , which can become part of C ++ 1z according to the latest Herb Sutter post.

I believe gcc allows this as an extension, and if we compile your program with -pedanticgcc will warn:

 warning: ISO C++ forbids use of 'auto' in parameter declaration [-Wpedantic]
 auto func(auto x)
           ^

, , :

auto func(auto x)
{
    std::cout << x << std::endl;
    return x.getx();
}

:

template <typename T1>
auto func(T1 x)
{
    std::cout << x << std::endl;
    return x.getx();
}

, , x int. , gcc ( ):

error: request for member 'getx' in 'x', which is of non-class type 'int'
     return x.getx();
                   ^

5.1.1 [dcl.fct]:

- , . [: . -end note] [: ,

auto f(auto x, const Regular& y);

template<typename T1, Regular T2>
  auto f(T1 x, const T2&);

-end ]

+5

auto , .

auto func(auto x) template<typename T> auto func(T x)

, .

+1

Source: https://habr.com/ru/post/1615027/


All Articles