What does `auto &&i = foo();` mean - c++11

Please explain how auto type deduction works when used with move semantic:
#include <iostream>
template <typename T>
struct A {
static void type() { std::cout << __PRETTY_FUNCTION__ << std::endl; }
};
float& bar() {
static float t = 5.5;
return t;
}
int foo() {
return 5;
}
int main() {
auto &&a1 = foo(); // I expected auto -> int (wrong)
auto &&a2 = bar(); // I expected auto -> float& (correct)
A<decltype(a1)>::type();
A<decltype(a2)>::type();
}
The output is:
static void A<T>::type() [with T = int&&]
static void A<T>::type() [with T = float&]

auto&& (just like T&& in parameter of a function template where T is a template parameter of that function template) follows slightly different rules than other deductions - it's unofficially called a "universal reference."
The idea is that if the initialiser is an lvalue of type X, the auto is deduced to X&. If it's an rvalue of type X, the auto is deduced to X. In both cases, && is then applied normally. From reference collapsing rules, X& && becomes X&, while X && remains X&&.
This means that in your a1 case, auto is indeed deduced to int, but a1 is then naturally declared with type int&&, and that's what decltype(a1) gives you.
At the same time, the auto in a2 is float&, and so is the type of a2, which the decltype(a2) again confirms.
In other words, your expectation that auto -> int in the first case is correct, but the type of a1 is auto &&a1, not just auto a1.

auto &&a1 = foo();
Return type of foo() is int. Since you declared a1 as auto&&, it expands to int&&, and that is what you get for type of a1.
auto &&a2 = bar();
Return type of bar() is float&. Since you declared a2 as auto&&, it expands to float& && and that converts to float& following the rules.
This answer explains the rules how the universal reference expands :
&& -> &&
&& & -> &
& && -> &
&& && -> &&

Related

SFINAE fails with template non-type reference argument

Consider this code:
constexpr int XX = 10;
template < auto& II > struct Ban { };
template < auto& II >
std:: true_type test(Ban<II>*);
std::false_type test(...);
and:
using BB = decltype(test(std::declval<Ban<XX>*>()));
Here I am expecting BB to be std::true_type, but it is std::false_type for both gcc-8.3 and clang-8.0. Is this a bug in these compilers?
Note that BB becomes std::true_type when I change auto& to auto. Also note that for gcc situation is the same if I use int const instead of auto, so int const& yields to std::false_type, while int const yields to std::true_type, while for clang int const& yields to std::true_type. You can find live example here.
Is there a workaround to do this kind of SFINAE with a template of non-type reference? The point is to have a utility like IsInstantiationOfBan.
Maybe instead of auto & you want decltype(auto):
#include <type_traits>
constexpr int XX = 10;
template <decltype(auto) II > struct Ban { };
template <decltype(auto) II >
std::true_type test(Ban<II>*);
std::false_type test(...);
int main()
{
using BB = decltype(test(std::declval<Ban<(XX)>*>()));
// ^ ^ be careful for brackets!
static_assert(std::is_same_v<BB, std::true_type>);
return 0;
}
[live demo]
In case of your first question, clang probably requires the const specifier before auto & to fulfil const correctness (constexpr variable is also presumably const). [example].

C++11/14 friend operator with template template parameter overloading

In the following code, I wanted to achieve the effect of binary operator chaining for the specific type definition I want to use - for trivial operator chaining, that a binary operator returns the same type of object, most of cases just simply returning *this, which could trivially be used again to chain the next object of the same type.
However, in my case, the binary operators takes two reference_wrappers of two same typed objects (awaitable<T>::ref) as input, and returns an aggregated object of type (awaitable<awaitable<T>::ref>), and I wanted to use the returned aggregate object to chain the next awaitable<T>::ref and again return the further aggregated object of type awaitable<awaitable<T>::ref> - notice that the returned object is always the same type of awaitable<awaitable<T>::ref>, no matter how many more chaining happens.
The friend operator with template template parameter defined at location (XXX) hoped to serve this purpose, but compilers don't seem to be willing to perform the bind.
Could anyone shed some lights on how I can achieve the result as described?
Thanks!
#include <functional>
template <typename T>
struct awaitable
{
typedef std::reference_wrapper<awaitable> ref;
// (A) - okay
friend awaitable<ref> operator||(ref a1, ref a2)
{
awaitable<ref> r;
return r;
}
// (XXX) - this doesn't bind
template < template <typename> class _awaitable >
friend awaitable<ref> operator||(typename awaitable<typename _awaitable<T>::ref>::ref a1, ref a2)
{
awaitable<ref> r;
return r;
}
};
int main(int argc, const char * argv[])
{
awaitable<void> a1;
awaitable<void> a2;
auto r1 = a1 || a2; // Okay - r1 is of type awaitable<awaitable<void>::ref>
awaitable<void> a3;
auto r3 = r1 || a3; // doesn't bind to the operator defined at XXX
return 0;
}
[EDIT] -
Answers in this post and this seem to explain the situation pretty nicely, but in my case, the friend operator has a template template parameter (which is needed to avoid recursive template instantiation), which might prevent the compilers to generate the correct namespace scope function when the template is instantiated?
It seems that the friend function with template template parameter makes template deduction fail. The solution is to remove the template template parameter, and expand the ::ref usage to std::reference_wrapper within the friend function definition:
#include <functional>
template <typename T>
struct awaitable
{
typedef std::reference_wrapper<awaitable> ref;
// (A) - okay
friend awaitable<ref> operator||(ref a1, ref a2)
{
awaitable<ref> r;
return r;
}
// (XXX) - removing the template template parameter makes the template instantiation for a specific type T to generate a namespace version of the function!
friend awaitable<ref> operator||(std::reference_wrapper<awaitable<std::reference_wrapper<awaitable<T>>>> a1, ref a2)
{
awaitable<ref> r;
return r;
}
};
// template <typename T>
// awaitable<typename awaitable<T>::ref> operator||(typename awaitable<typename awaitable<T>::ref>::ref a1, typename awaitable<T>::ref a2)
// {
// awaitable<typename awaitable<T>::ref> r;
// return r;
// }
int main(int argc, const char * argv[])
{
awaitable<void> a1;
awaitable<void> a2;
auto r1 = a1 || a2; // Okay - r1 is of type awaitable<awaitable<void>::ref>
awaitable<void> a3;
auto r3 = r1 || a3; // now it works!
return 0;
}
Demo here
is this what you need?
template < template <typename> class _awaitable, typename U >
friend auto operator||(_awaitable<std::reference_wrapper<U>> a1, ref a2)
{
awaitable<ref> r;
return r;
}
live demo
EDIT1
I saw your answer where you removed the template parameter to get it working. That works great if void is the only the type you use. If you try to use another type it will fail though. The closest I've got to get around it is explicity using std::ref(r1) e.g.
template<typename U>
friend awaitable<ref> operator||(std::reference_wrapper<awaitable<std::reference_wrapper<awaitable<U>>>> a1, ref a2)
{
std::cout << "(XXX2)" << std::endl;
awaitable<ref> r;
return r;
}
awaitable<int> a4;
auto r4 = std::ref(r1) || a4;
live demo 2

Variadic Template Recursion

I am trying to use recursion to solve this problem where if i call
decimal<0,0,1>();
i should get the decimal number (4 in this case).
I am trying to use recursion with variadic templates but cannot get it to work.
Here's my code;
template<>
int decimal(){
return 0;
}
template<bool a,bool...pack>
int decimal(){
cout<<a<<"called"<<endl;
return a*2 + decimal<pack...>();
};
int main(int argc, char *argv[]){
cout<<decimal<0,0,1>()<<endl;
return 0;
}
What would be the best way to solve this?
template<typename = void>
int decimal(){
return 0;
}
template<bool a,bool...pack>
int decimal(){
cout<<a<<"called"<<endl;
return a + 2*decimal<pack...>();
};
The problem was with the recursive case, where it expects to be able to call decltype<>(). That is what I have defined in the first overload above. You can essentially ignore the typename=void, the is just necessary to allow the first one to compile.
A possible solution can be the use of a constexpr function (so you can use it's values it's value run-time, when appropriate) where the values are argument of the function.
Something like
#include <iostream>
constexpr int decimal ()
{ return 0; }
template <typename T, typename ... packT>
constexpr int decimal (T const & a, packT ... pack)
{ return a*2 + decimal(pack...); }
int main(int argc, char *argv[])
{
constexpr int val { decimal(0, 0, 1) };
static_assert( val == 2, "!");
std::cout << val << std::endl;
return 0;
}
But I obtain 2, not 4.
Are you sure that your code should return 4?
-- EDIT --
As pointed by aschepler, my example decimal() template function return "eturns twice the sum of its arguments, which is not" what do you want.
Well, with 0, 1, true and false you obtain the same; with other number, you obtain different results.
But you can modify decimal() as follows
template <typename ... packT>
constexpr int decimal (bool a, packT ... pack)
{ return a*2 + decimal(pack...); }
to avoid this problem.
This is a C++14 solution. It is mostly C++11, except for std::integral_sequence nad std::index_sequence, both of which are relatively easy to implement in C++11.
template<bool...bs>
using bools = std::integer_sequence<bool, bs...>;
template<std::uint64_t x>
using uint64 = std::integral_constant< std::uint64_t, x >;
template<std::size_t N>
constexpr uint64< ((std::uint64_t)1) << (std::uint64_t)N > bit{};
template<std::uint64_t... xs>
struct or_bits : uint64<0> {};
template<std::int64_t x0, std::int64_t... xs>
struct or_bits<x0, xs...> : uint64<x0 | or_bits<xs...>{} > {};
template<bool...bs, std::size_t...Is>
constexpr
uint64<
or_bits<
uint64<
bs?bit<Is>:std::uint64_t(0)
>{}...
>{}
>
from_binary( bools<bs...> bits, std::index_sequence<Is...> ) {
(void)bits; // suppress warning
return {};
}
template<bool...bs>
constexpr
auto from_binary( bools<bs...> bits={} )
-> decltype( from_binary( bits, std::make_index_sequence<sizeof...(bs)>{} ) )
{ return {}; }
It generates the resulting value as a type with a constexpr conversion to scalar. This is slightly more powerful than a constexpr function in its "compile-time-ness".
It assumes that the first bit is the most significant bit in the list.
You can use from_binary<1,0,1>() or from_binary( bools<1,0,1>{} ).
Live example.
This particular style of type-based programming results in code that does all of its work in its signature. The bodies consist of return {};.

remove_if on a map trying to pass a const as a non-const - why?

Here's a bit of code which is supposed to filter out the elements of a map which satisfy a predicate, into a new map (MCVE-fied):
#include <algorithm>
#include <unordered_map>
#include <iostream>
using namespace std;
int main() {
unordered_map<string, int> m = { { "hello", 1 }, { "world", 2 } };
auto p = [](const decltype(m)::value_type& e) { return e.second == 2; };
const auto& m2(m);
auto m3(m2);
auto it = remove_if(m3.begin(), m3.end(), p);
m3.erase(it, m3.end());
cout << "m3.size() = " << m3.size() << endl;
return 0;
}
Compilation fails on the remove_if() line, and I get:
In file included from /usr/include/c++/4.9/utility:70:0,
from /usr/include/c++/4.9/algorithm:60,
from /tmp/b.cpp:1:
/usr/include/c++/4.9/bits/stl_pair.h: In instantiation of ‘std::pair<_T1, _T2>& std::pair<_T1, _T2>::operator=(std::pair<_T1, _T2>&&) [with _T1 = const std::basic_string<char>; _T2 = int]’:
/usr/include/c++/4.9/bits/stl_algo.h:868:23: required from ‘_ForwardIterator std::__remove_if(_ForwardIterator, _ForwardIterator, _Predicate) [with _ForwardIterator = std::__detail::_Node_iterator<std::pair<const std::basic_string<char>, int>, false, true>; _Predicate = __gnu_cxx::__ops::_Iter_pred<main()::<lambda(const value_type&)> >]’
/usr/include/c++/4.9/bits/stl_algo.h:937:47: required from ‘_FIter std::remove_if(_FIter, _FIter, _Predicate) [with _FIter = std::__detail::_Node_iterator<std::pair<const std::basic_string<char>, int>, false, true>; _Predicate = main()::<lambda(const value_type&)>]’
/tmp/b.cpp:12:48: required from here
/usr/include/c++/4.9/bits/stl_pair.h:170:8: error: passing ‘const std::basic_string<char>’ as ‘this’ argument of ‘std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(const std::basic_string<_CharT, _Traits, _Alloc>&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’ discards qualifiers [-fpermissive]
first = std::forward<first_type>(__p.first);
^
Why is this happening? remove_if should not need non-const map keys (strings in this case) - if I am not mistaken. Perhaps the autos assume somehow I want non-const iterators? If so, what do I do other tha spelling out the type (I want to avoid that since this code needs to be templated).
Your example fails even without all those intermediate variables.
unordered_map<string, int> m = { { "hello", 1 }, { "world", 2 } };
auto p = [](const decltype(m)::value_type& e) { return e.second == 2; };
auto it = remove_if(m.begin(), m.end(), p);
The code above will fail with the same errors. You can't use remove_if with associative containers because the algorithm works by moving elements that satisfy your predicate to the end of the container. But how would you reorder an unordered_map?
Write a loop for erasing elements
for(auto it = m.begin(); it != m.end();)
{
if(p(*it)) it = m.erase(it);
else ++it;
}
Or you could package that into an algorithm
template<typename Map, typename Predicate>
void map_erase_if(Map& m, Predicate const& p)
{
for(auto it = m.begin(); it != m.end();)
{
if(p(*it)) it = m.erase(it);
else ++it;
}
}
If you have a standard library implementation that implements the uniform container erasure library fundamentals extensions, then you have an algorithm similar to the one above in the std::experimental namespace.
Don't use std::remove_if for node-based containers. The algorithm attempts to permute the collection, which you either cannot do (for associative containers) or which is inefficient (for lists).
For associative containers, you'll need a normal loop:
for (auto it = m.begin(); it != m.end(); )
{
if (it->second == 2) { m.erase(it++); }
else { ++it; }
}
If you're removing from a list, use the remove member function instead, which takes a predicate.
From cppreference:
Removing is done by shifting (by means of move assignment) the elements in the range in such a way that the elements that are not to be removed appear in the beginning of the range.
You can't reorder the elements in an associative container, for the unordered_map this doesn't make sense because moving the elements to the end doesn't mean anything, they are looked up by keys anyway.

Return type of wrapper function C++11

I have re-arranged an example regarding the std::forward with template.
I have used a wrapper function and everything is fine, if i declare it as void function. It works as expected.
#include<iostream>
using namespace std;
template <typename T, typename U>
auto summation(T const &a, U const& b) -> decltype(T{}, U{}) {
cout << "call by lvalue" << endl;
return a+b;
}
template <typename T, typename U>
auto summation(T&& a, U && b) -> decltype(T{},U{}) {
cout << "call by rvalue" << endl;
return a+b;
}
template<typename T,typename U> void func(T&& a, U && b) {
summation(forward<T>(a), forward<U>(b));
}
int main() {
int x = 10;
double y = 20;
func(x,y);
func(10,20);
}
but if I want to return a type from a wrapper function, no matter what I used, I got error on lvalues function call ONLY, fund(x,y), stating "....function does not match the arguments"... the other fund(10,20) works.
template<typename T,typename U> auto func(T&& a, U && b) -> decltype(T{}, U{}) {
return summation(forward<T>(a), forward<U>(b));
}
and even using c++14 decltype(auto) for deducing the return type of forwarding functions and similar wrappers
template<typename T,typename U> decltype(auto) func(T&& a, U && b) {
return summation(forward<T>(a), forward<U>(b));
}
it does not work either, stating "decline(type) is C++o1 extension..." that, thank you compiler, but it does help.
One non sense horrible solution is declare the return type or T or U as return type. This compiles even if I got a warning stating "Reference to stack memory associated to local variable returned"
template<typename T,typename U> U func(T&& a, U && b) {
auto res = summation(forward<T>(a), forward<U>(b));
return res;
}
the return type of std::forward given (t) the object to be forwarded is
static_cast<T&&>(t)
therefore it the first solution with auto should work but it does not.
Any suggestion on this ?
Thanks for any help
decltype means the type of the expression given in its argument. So
decltype(T {}, U {})
will be the type of the expression T{}, U{}. You have the comma operator here, and so the type of the expression is the type of the expression after the comma, which is U{}, hence decltype (T{}, U{}) gives you type U (more precisely, U &&, I guess, since it is an rvalue).
What you want is
decltype(T{} + U{})
or
decltype(a+b)
(thanks to Jonathan Wakely, see comments).

Resources