EzDevInfo.com

auto

A collection of source code generators for Java.

Why can I use auto on a private type?

I was somehow surprised that the following code compiles and run (vc2012 & gcc4.7.2)

class Foo {
    struct Bar { int i; };
public:
    Bar Baz() { return Bar(); }
};

int main() {
    Foo f;
    // Foo::Bar b = f.Baz();  // error
    auto b = f.Baz();         // ok
    std::cout << b.i;
}

Is it correct that this code compiles fine? And why is it correct? Why can I use auto on a private type, while I can't use its name (as expected)?


Source: (StackOverflow)

C++ auto keyword. Why is it magic?

From all the material I used to learn C++, auto has always been a weird storage duration specifier that didn't serve any purpose. But just recently, I encountered code that used it as a type name in and of itself. Out of curiosity I tried it, and it assumes the type of whatever I happen to assign to it!

Suddenly STL iterators and, well, anything at all that uses templates is 10 fold easier to write. It feels like I'm using a 'fun' language like Python.

Where has this keyword been my whole life? Will you dash my dreams by saying it's exclusive to visual studio or not portable?


Source: (StackOverflow)

Advertisements

Why does auto return type change the overload resolution?

Thanks to decltype as a return type, C++11 made it extremely easy to introduce decorators. For instance, consider this class:

struct base
{
  void fun(unsigned) {}
};

I want to decorate it with additional features, and since I will do that several times with different kinds of decorations, I first introduce a decorator class that simply forwards everything to base. In the real code, this is done via std::shared_ptr so that I can remove decorations and recover the "naked" object, and everything is templated.

#include <utility> // std::forward
struct decorator
{
  base b;

  template <typename... Args>
  auto
  fun(Args&&... args)
    -> decltype(b.fun(std::forward<Args>(args)...))
  {
    return b.fun(std::forward<Args>(args)...);
  }
};

Perfect forwarding and decltype are just wonderful. In the real code, I actually use a macro that just needs the name of the function, all the rest is boilerplate.

And then, I can introduce a derived class that adds features to my object (derived is improper, agreed, but it helps understanding that derived is-a-kind of base, albeit not via inheritance).

struct foo_t {};
struct derived : decorator
{
  using decorator::fun; // I want "native" fun, and decorated fun.
  void fun(const foo_t&) {}
};

int main()
{
  derived d;
  d.fun(foo_t{});
}

Then C++14 came, with return type deduction, which allows to write things in a simpler way: remove the decltype part of the forwarding function:

struct decorator
{
  base b;

  template <typename... Args>
  auto
  fun(Args&&... args)
  {
    return b.fun(std::forward<Args>(args)...);
  }
};

And then it breaks. Yes, at least according to both GCC and Clang, this:

  template <typename... Args>
  auto
  fun(Args&&... args)
    -> decltype(b.fun(std::forward<Args>(args)...))
  {
    return b.fun(std::forward<Args>(args)...);
  }
};

is not equivalent to this (and the issue is not auto vs. decltype(auto)):

  template <typename... Args>
  auto
  fun(Args&&... args)
  {
    return b.fun(std::forward<Args>(args)...);
  }
};

The overload resolution seems to be completely different and it ends like this:

clang++-mp-3.5 -std=c++1y main.cc
main.cc:19:18: error: no viable conversion from 'foo_t' to 'unsigned int'
    return b.fun(std::forward<Args>(args)...);
                 ^~~~~~~~~~~~~~~~~~~~~~~~
main.cc:32:5: note: in instantiation of function template specialization
      'decorator::fun<foo_t>' requested here
  d.fun(foo_t{});
    ^
main.cc:7:20: note: passing argument to parameter here
  void fun(unsigned) {}
                   ^

I understand the failure: my call (d.fun(foo_t{})) does not match perfectly with the signature of derived::fun, which takes a const foo_t&, so the very eager decorator::fun kicks in (we know how Args&&... is extremely impatient to bind to anything that does not match perfectly). So it forwards this to base::fun which can't deal with foo_t.

If I change derived::fun to take a foo_t instead of const foo_t&, then it works as expected, which shows that indeed here the problem is that there is a competition between derived::fun and decorator::fun.

However why the heck does this show with return-type deduction??? And more precisely why was this behavior chosen by the committee?

To make things easier, on Coliru:

Thanks!


Source: (StackOverflow)

How does generic lambda work in C++14?

How does generic lambda work (auto keyword as an argument type) in C++14 standard?

Is it based on C++ templates where for each different argument type compiler generates a new function with the same body but replaced types (compile-time polymorphism) or is it more similar to Java's generics (type erasure)?

Code example:

auto glambda = [](auto a) { return a; };

Source: (StackOverflow)

The relationship between auto and decltype

Is

auto x = initializer;

equivalent to

decltype(initializer) x = initializer;

or

decltype((initializer)) x = initializer;

or neither?


Source: (StackOverflow)

What is the type of lambda when deduced with "auto" in C++11?

I had a perception that, type of a lambda is a function pointer. When I performed following test, I found it to be wrong (demo).

#define LAMBDA [] (int i) -> long { return 0; }
int main ()
{
  long (*pFptr)(int) = LAMBDA;  // ok
  auto pAuto = LAMBDA;  // ok
  assert(typeid(pFptr) == typeid(pAuto));  // assertion fails !
}

Is above code missing any point ? If not then, what is the typeof a lambda expression when deduced with auto keyword ?


Source: (StackOverflow)

Is there auto type infering in Java?

Is there an auto variable type in Java like you have in C++?

An example:

for ( auto var : object_array)
    std::cout << var << std::endl;

for( auto var : object_array)
    var.do_something_that_only_this_particular_obj_can_do();

I know that there is an enhanced for loop in Java, but is there an auto? If not, is there a hack to doing this? I am referring to the new feature in C++11


Source: (StackOverflow)

A lambda's return type can be deduced by the return value, so why can't a function's?

#include <iostream>

int main(){

    auto lambda = [] {
        return 7;
    };

    std::cout << lambda() << '\n';

}

This program compiles and prints 7.
The return type of the lambda is deduced to the integer type based on the return value of 7.


Why isn't this possible with ordinary functions?

#include <iostream>

auto function(){
    return 42;
}

int main(){

    std::cout << function() << '\n';
}

error: ‘function’ function uses ‘auto’ type specifier without trailing return type


Source: (StackOverflow)

Can the use of C++11's 'auto' improve performance?

I can see why the auto type in C++11 improves correctness and maintainability. I've read that it can also improve performance (Almost Always Auto by Herb Sutter), but I miss a good explanation.

  • How can auto improve performance?
  • Can anyone give an example?

Source: (StackOverflow)

Why does auto a=1; compile in C?

The code:

int main(void)
{
    auto a=1;
    return 0;
}

gets compiled without errors by the MS Visual Studio 2012 compiler, when the file has the .c extension. I have always thought that when you use the .c extension, compilation should be according to the C syntax, and not C++. Moreover, as far as I know auto without a type is allowed only in C++ since C++11, where it means that the type is deduced from the initializer.

Does that mean that my compiler isn't sticking to C, or is the code actually correct in C-language?


Source: (StackOverflow)

How much is too much with C++11 auto keyword?

I've been using the new auto keyword available in the C++11 standard for complicated templated types which is what I believe it was designed for. But I'm also using it for things like:

auto foo = std::make_shared<Foo>();

And more skeptically for:

auto foo = bla(); // where bla() return a shared_ptr<Foo>

I haven't seen much discussion on this topic. It seems that auto could be overused, since a type is often a form of documentation and sanity checks. Where do you draw the line in using auto and what are the recommended use cases for this new feature?

To clarify: I'm not asking for a philosophical opinion; I'm asking for the intended use of this keyword by the standard committee, possibly with comments on how that intended use is realized in practice.

Side note: This question was moved to SE.Programmers and then back to Stack Overflow. Discussion about this can be found in this meta question.


Source: (StackOverflow)

What does auto&& tell us?

If you read code like

auto&& var = foo();

where foo is any function retuning by value of type T. Then var is an lvalue of type rvalue reference to T. But what does this imply for var? Does it mean, we are allowed to steal the resources of var? Are there any reasonable situations when you should use auto&& to tell the reader of your code something like you do when you return a unique_ptr<> to tell that you have exclusive ownership? And what about for example T&& when T is of class type?

I just want to understand, if there are any other use cases of auto&& than those in template programming like discussed in the examples in this article Universal References by Scott Meyers.


Source: (StackOverflow)

Does auto return type deduction force multiple functions to have the same return type?

Consider the below snippet:

struct A
{
  auto foo(), bar();
};

auto A::foo() { return 1; }
auto A::bar() { return 'a'; }

int main()
{

}

It compiles fine in Clang++ 3.7.0.

It fails in G++ 5.2.0:

main.cpp: In member function 'auto A::bar()':
main.cpp:7:24: error: inconsistent deduction for 'auto': 'int' and then 'char'
auto A::bar() { return 'a'; }

Does auto return type deduction force multiple functions, declared in a single statement, to have the same return type?


Source: (StackOverflow)

Should the trailing return type syntax style become the default for new C++11 programs?

C++11 supports a new function syntax:

auto func_name(int x, int y) -> int;

Currently this function would be declared as:

int func_name(int x, int y);

The new style does not seem to be widely adopted yet (say in the gcc stl)

However, should this new style be preferred everywhere in new C++11-programs, or will it only be used when needed?

Personally, I prefer the old style when possible, but a code-base with mixed styles looks pretty ugly.


Source: (StackOverflow)

Usage of auto in C++11

When I use auto to deduce a pointer type, I found a weird phenomenon. My code is like this:

#include <iostream>
using namespace std;
int main()
{
    int i = 100;
    auto p1 = &i;
    auto *p2 = &i;

    cout << *p1 << " " << *p2 << endl;

    return 0;
}

After compiling and executing, we can find that the result of *p1 and *p2 is the same, both 100. This means p1 and p2 are both a pointer object which points to an int object.

[user@host ~]$ ./test 
100 100

Is there any difference between these two statements which define p1 and p2?


Source: (StackOverflow)