Why does lambda auto& parameter choose const overload?C++ error in ios_base.hWhy does changing 0.1f to 0...

Slow moving projectiles from a hand-held weapon - how do they reach the target?

If I delete my router's history can my ISP still provide it to my parents?

How to prevent cleaner from hanging my lock screen in Ubuntu 16.04

Citing paywalled articles accessed via illegal web sharing

Process to change collation on a database

How should I handle players who ignore the session zero agreement?

Can I become debt free or should I file for bankruptcy? How do I manage my debt and finances?

Is it a fallacy if someone claims they need an explanation for every word of your argument to the point where they don't understand common terms?

Am I a Rude Number?

Would a National Army of mercenaries be a feasible idea?

What's the most convenient time of year to end the world?

How to convert a ListContourPlot into primitive usable with Graphics3D?

Why does String.replaceAll() work differently in Java 8 from Java 9?

What makes the Forgotten Realms "forgotten"?

Can an insurance company drop you after receiving a bill and refusing to pay?

Can a dragon be stuck looking like a human?

What is better: yes / no radio, or simple checkbox?

Disable the ">" operator in Rstudio linux terminal

Is there any differences between "Gucken" and "Schauen"?

How do I say "Brexit" in Latin?

Strange Sign on Lab Door

why a subspace is closed?

How can animals be objects of ethics without being subjects as well?

Why do members of Congress in committee hearings ask witnesses the same question multiple times?



Why does lambda auto& parameter choose const overload?


C++ error in ios_base.hWhy does changing 0.1f to 0 slow down performance by 10x?error while working with boost::sregex_token_iteratorCalling member's overloaded << operator in C++Why does outputting a class with a conversion operator not work for std::string?Use boost bind to output map dataGetting very long “No match for 'operator+'” error in C++Using my custom iterator with stl algorithmsWhy does my program run fine on Windows but not linux?what does compiler when operator<<(std::basic_ostream) overloaded as friend













15















I'm trying to implement a class which wraps an arbitrary type and a mutex. To access the wrapped data, one needs to pass a functor as parameter of the locked method. The wrapper class will then pass the wrapped data as parameter to the functor.



I'd like my wrapper class to work with const & non-const, so I tried the following



#include <mutex>
#include <string>

template<typename T, typename Mutex = std::mutex>
class Mutexed
{
private:
T m_data;
mutable Mutex m_mutex;

public:
using type = T;
using mutex_type = Mutex;

public:
explicit Mutexed() = default;

template<typename... Args>
explicit Mutexed(Args&&... args)
: m_data{std::forward<Args>(args)...}
{}

template<typename F>
auto locked(F&& f) -> decltype(std::forward<F>(f)(m_data)) {
std::lock_guard<Mutex> lock(m_mutex);
return std::forward<F>(f)(m_data);
}

template<typename F>
auto locked(F&& f) const -> decltype(std::forward<F>(f)(m_data)) {
std::lock_guard<Mutex> lock(m_mutex);
return std::forward<F>(f)(m_data);
}
};

int main()
{
Mutexed<std::string> str{"Foo"};

str.locked([](auto &s) { /* this doesn't compile */
s = "Bar";
});

str.locked([](std::string& s) { /* this compiles fine */
s = "Baz";
});
return 0;
}


The first locked call with the generic lambda fails to compile with the following error



/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp: In instantiation of ‘main()::<lambda(auto:1&)> [with auto:1 = const std::__cxx11::basic_string<char>]’:
/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:30:60: required by substitution of ‘template<class F> decltype (forward<F>(f)(((const Mutexed<T, Mutex>*)this)->Mutexed<T, Mutex>::m_data)) Mutexed<T, Mutex>::locked(F&&) const [with F = main()::<lambda(auto:1&)>]’
/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:42:6: required from here
/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:41:11: error: passing ‘const std::__cxx11::basic_string<char>’ as ‘this’ argument discards qualifiers [-fpermissive]
s = "Bar";
^
In file included from /usr/include/c++/5/string:52:0,
from /usr/include/c++/5/stdexcept:39,
from /usr/include/c++/5/array:38,
from /usr/include/c++/5/tuple:39,
from /usr/include/c++/5/mutex:38,
from /home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:1:
/usr/include/c++/5/bits/basic_string.h:558:7: note: in call to ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator=(const _CharT*) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
operator=(const _CharT* __s)
^


But the second call with the std::string& parameter is fine.



Why is that ? And is there a way to make it work as expected while using a generic lambda ?










share|improve this question























  • @YSC A lambda, generic or otherwise, is a class, not a class template. F is happily resolved to that class. The fact that the class has member templates is irrelevant at that point.

    – Igor Tandetnik
    14 hours ago


















15















I'm trying to implement a class which wraps an arbitrary type and a mutex. To access the wrapped data, one needs to pass a functor as parameter of the locked method. The wrapper class will then pass the wrapped data as parameter to the functor.



I'd like my wrapper class to work with const & non-const, so I tried the following



#include <mutex>
#include <string>

template<typename T, typename Mutex = std::mutex>
class Mutexed
{
private:
T m_data;
mutable Mutex m_mutex;

public:
using type = T;
using mutex_type = Mutex;

public:
explicit Mutexed() = default;

template<typename... Args>
explicit Mutexed(Args&&... args)
: m_data{std::forward<Args>(args)...}
{}

template<typename F>
auto locked(F&& f) -> decltype(std::forward<F>(f)(m_data)) {
std::lock_guard<Mutex> lock(m_mutex);
return std::forward<F>(f)(m_data);
}

template<typename F>
auto locked(F&& f) const -> decltype(std::forward<F>(f)(m_data)) {
std::lock_guard<Mutex> lock(m_mutex);
return std::forward<F>(f)(m_data);
}
};

int main()
{
Mutexed<std::string> str{"Foo"};

str.locked([](auto &s) { /* this doesn't compile */
s = "Bar";
});

str.locked([](std::string& s) { /* this compiles fine */
s = "Baz";
});
return 0;
}


The first locked call with the generic lambda fails to compile with the following error



/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp: In instantiation of ‘main()::<lambda(auto:1&)> [with auto:1 = const std::__cxx11::basic_string<char>]’:
/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:30:60: required by substitution of ‘template<class F> decltype (forward<F>(f)(((const Mutexed<T, Mutex>*)this)->Mutexed<T, Mutex>::m_data)) Mutexed<T, Mutex>::locked(F&&) const [with F = main()::<lambda(auto:1&)>]’
/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:42:6: required from here
/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:41:11: error: passing ‘const std::__cxx11::basic_string<char>’ as ‘this’ argument discards qualifiers [-fpermissive]
s = "Bar";
^
In file included from /usr/include/c++/5/string:52:0,
from /usr/include/c++/5/stdexcept:39,
from /usr/include/c++/5/array:38,
from /usr/include/c++/5/tuple:39,
from /usr/include/c++/5/mutex:38,
from /home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:1:
/usr/include/c++/5/bits/basic_string.h:558:7: note: in call to ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator=(const _CharT*) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
operator=(const _CharT* __s)
^


But the second call with the std::string& parameter is fine.



Why is that ? And is there a way to make it work as expected while using a generic lambda ?










share|improve this question























  • @YSC A lambda, generic or otherwise, is a class, not a class template. F is happily resolved to that class. The fact that the class has member templates is irrelevant at that point.

    – Igor Tandetnik
    14 hours ago
















15












15








15


0






I'm trying to implement a class which wraps an arbitrary type and a mutex. To access the wrapped data, one needs to pass a functor as parameter of the locked method. The wrapper class will then pass the wrapped data as parameter to the functor.



I'd like my wrapper class to work with const & non-const, so I tried the following



#include <mutex>
#include <string>

template<typename T, typename Mutex = std::mutex>
class Mutexed
{
private:
T m_data;
mutable Mutex m_mutex;

public:
using type = T;
using mutex_type = Mutex;

public:
explicit Mutexed() = default;

template<typename... Args>
explicit Mutexed(Args&&... args)
: m_data{std::forward<Args>(args)...}
{}

template<typename F>
auto locked(F&& f) -> decltype(std::forward<F>(f)(m_data)) {
std::lock_guard<Mutex> lock(m_mutex);
return std::forward<F>(f)(m_data);
}

template<typename F>
auto locked(F&& f) const -> decltype(std::forward<F>(f)(m_data)) {
std::lock_guard<Mutex> lock(m_mutex);
return std::forward<F>(f)(m_data);
}
};

int main()
{
Mutexed<std::string> str{"Foo"};

str.locked([](auto &s) { /* this doesn't compile */
s = "Bar";
});

str.locked([](std::string& s) { /* this compiles fine */
s = "Baz";
});
return 0;
}


The first locked call with the generic lambda fails to compile with the following error



/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp: In instantiation of ‘main()::<lambda(auto:1&)> [with auto:1 = const std::__cxx11::basic_string<char>]’:
/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:30:60: required by substitution of ‘template<class F> decltype (forward<F>(f)(((const Mutexed<T, Mutex>*)this)->Mutexed<T, Mutex>::m_data)) Mutexed<T, Mutex>::locked(F&&) const [with F = main()::<lambda(auto:1&)>]’
/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:42:6: required from here
/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:41:11: error: passing ‘const std::__cxx11::basic_string<char>’ as ‘this’ argument discards qualifiers [-fpermissive]
s = "Bar";
^
In file included from /usr/include/c++/5/string:52:0,
from /usr/include/c++/5/stdexcept:39,
from /usr/include/c++/5/array:38,
from /usr/include/c++/5/tuple:39,
from /usr/include/c++/5/mutex:38,
from /home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:1:
/usr/include/c++/5/bits/basic_string.h:558:7: note: in call to ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator=(const _CharT*) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
operator=(const _CharT* __s)
^


But the second call with the std::string& parameter is fine.



Why is that ? And is there a way to make it work as expected while using a generic lambda ?










share|improve this question














I'm trying to implement a class which wraps an arbitrary type and a mutex. To access the wrapped data, one needs to pass a functor as parameter of the locked method. The wrapper class will then pass the wrapped data as parameter to the functor.



I'd like my wrapper class to work with const & non-const, so I tried the following



#include <mutex>
#include <string>

template<typename T, typename Mutex = std::mutex>
class Mutexed
{
private:
T m_data;
mutable Mutex m_mutex;

public:
using type = T;
using mutex_type = Mutex;

public:
explicit Mutexed() = default;

template<typename... Args>
explicit Mutexed(Args&&... args)
: m_data{std::forward<Args>(args)...}
{}

template<typename F>
auto locked(F&& f) -> decltype(std::forward<F>(f)(m_data)) {
std::lock_guard<Mutex> lock(m_mutex);
return std::forward<F>(f)(m_data);
}

template<typename F>
auto locked(F&& f) const -> decltype(std::forward<F>(f)(m_data)) {
std::lock_guard<Mutex> lock(m_mutex);
return std::forward<F>(f)(m_data);
}
};

int main()
{
Mutexed<std::string> str{"Foo"};

str.locked([](auto &s) { /* this doesn't compile */
s = "Bar";
});

str.locked([](std::string& s) { /* this compiles fine */
s = "Baz";
});
return 0;
}


The first locked call with the generic lambda fails to compile with the following error



/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp: In instantiation of ‘main()::<lambda(auto:1&)> [with auto:1 = const std::__cxx11::basic_string<char>]’:
/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:30:60: required by substitution of ‘template<class F> decltype (forward<F>(f)(((const Mutexed<T, Mutex>*)this)->Mutexed<T, Mutex>::m_data)) Mutexed<T, Mutex>::locked(F&&) const [with F = main()::<lambda(auto:1&)>]’
/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:42:6: required from here
/home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:41:11: error: passing ‘const std::__cxx11::basic_string<char>’ as ‘this’ argument discards qualifiers [-fpermissive]
s = "Bar";
^
In file included from /usr/include/c++/5/string:52:0,
from /usr/include/c++/5/stdexcept:39,
from /usr/include/c++/5/array:38,
from /usr/include/c++/5/tuple:39,
from /usr/include/c++/5/mutex:38,
from /home/foo/tests/lamdba_auto_const/lambda_auto_const/main.cpp:1:
/usr/include/c++/5/bits/basic_string.h:558:7: note: in call to ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>& std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator=(const _CharT*) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
operator=(const _CharT* __s)
^


But the second call with the std::string& parameter is fine.



Why is that ? And is there a way to make it work as expected while using a generic lambda ?







c++ templates c++14 generic-lambda






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 15 hours ago









UndaUnda

1,21031927




1,21031927













  • @YSC A lambda, generic or otherwise, is a class, not a class template. F is happily resolved to that class. The fact that the class has member templates is irrelevant at that point.

    – Igor Tandetnik
    14 hours ago





















  • @YSC A lambda, generic or otherwise, is a class, not a class template. F is happily resolved to that class. The fact that the class has member templates is irrelevant at that point.

    – Igor Tandetnik
    14 hours ago



















@YSC A lambda, generic or otherwise, is a class, not a class template. F is happily resolved to that class. The fact that the class has member templates is irrelevant at that point.

– Igor Tandetnik
14 hours ago







@YSC A lambda, generic or otherwise, is a class, not a class template. F is happily resolved to that class. The fact that the class has member templates is irrelevant at that point.

– Igor Tandetnik
14 hours ago














1 Answer
1






active

oldest

votes


















19














This is a problem fundamentally with what happens with SFINAE-unfriendly callables. For more reference, check out P0826.



The problem is, when you call this:



 str.locked([](auto &s) { s = "Bar"; });


We have two overloads of locked and we have to try both. The non-const overload works fine. But the const one – even if it won't be selected by overload resolution anyway – still has to be instantiated (it's a generic lambda, so to figure out what decltype(std::forward<F>(f)(m_data)) might be you have to instantiate it) and that instantiation fails within the body of the lambda. The body is outside of the immediate context, so it's not a substitution failure – it's a hard error.



When you call this:



str.locked([](std::string& s) { s = "Bar"; });


We don't need to look at the body at all during the whole process of overload resolution – we can simply reject at the call site (since you can't pass a const string into a string&).



There's not really a solution to this problem in the language today – you basically have to add constraints on your lambda to ensure that the instantiation failure happens in the immediate context of substitution rather than in the body. Something like:



str.locked([](auto &s) -> decltype(s = std::string(), void()) {
s = "Bar";
});




A more thorough language solution would have been to allow for "Deducing this" (see the section in the paper about this specific problem). But that won't be in C++20.






share|improve this answer





















  • 5





    Well this is a shame. +1 as this had me really scratching my head. I couldn't figure out why it was calling the const version, and as you point out it really isn't, it just has to check, and the check results in a hard error.

    – NathanOliver
    14 hours ago











  • Thank you for this explanation. Could you elaborate on "The body is outside of the immediate context" a bit though? (I'm unclear of what exactly is the immediate context)

    – YSC
    14 hours ago













  • Thank you for the explanation and the workaround. It works, but since it's more verbose than writing the type, I'll do that instead of using auto for this case. I'll check out the paper too.

    – Unda
    14 hours ago











  • Would it work if you took the parameter as an auto&& parameter (though then you can pass rvalues, which you don't really want to allow)?

    – Nicol Bolas
    12 hours ago








  • 1





    @Unda Yeah, if you want to call it like locked(str, []{...}) instead. Just changes the syntax.

    – Barry
    8 hours ago











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54947560%2fwhy-does-lambda-auto-parameter-choose-const-overload%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









19














This is a problem fundamentally with what happens with SFINAE-unfriendly callables. For more reference, check out P0826.



The problem is, when you call this:



 str.locked([](auto &s) { s = "Bar"; });


We have two overloads of locked and we have to try both. The non-const overload works fine. But the const one – even if it won't be selected by overload resolution anyway – still has to be instantiated (it's a generic lambda, so to figure out what decltype(std::forward<F>(f)(m_data)) might be you have to instantiate it) and that instantiation fails within the body of the lambda. The body is outside of the immediate context, so it's not a substitution failure – it's a hard error.



When you call this:



str.locked([](std::string& s) { s = "Bar"; });


We don't need to look at the body at all during the whole process of overload resolution – we can simply reject at the call site (since you can't pass a const string into a string&).



There's not really a solution to this problem in the language today – you basically have to add constraints on your lambda to ensure that the instantiation failure happens in the immediate context of substitution rather than in the body. Something like:



str.locked([](auto &s) -> decltype(s = std::string(), void()) {
s = "Bar";
});




A more thorough language solution would have been to allow for "Deducing this" (see the section in the paper about this specific problem). But that won't be in C++20.






share|improve this answer





















  • 5





    Well this is a shame. +1 as this had me really scratching my head. I couldn't figure out why it was calling the const version, and as you point out it really isn't, it just has to check, and the check results in a hard error.

    – NathanOliver
    14 hours ago











  • Thank you for this explanation. Could you elaborate on "The body is outside of the immediate context" a bit though? (I'm unclear of what exactly is the immediate context)

    – YSC
    14 hours ago













  • Thank you for the explanation and the workaround. It works, but since it's more verbose than writing the type, I'll do that instead of using auto for this case. I'll check out the paper too.

    – Unda
    14 hours ago











  • Would it work if you took the parameter as an auto&& parameter (though then you can pass rvalues, which you don't really want to allow)?

    – Nicol Bolas
    12 hours ago








  • 1





    @Unda Yeah, if you want to call it like locked(str, []{...}) instead. Just changes the syntax.

    – Barry
    8 hours ago
















19














This is a problem fundamentally with what happens with SFINAE-unfriendly callables. For more reference, check out P0826.



The problem is, when you call this:



 str.locked([](auto &s) { s = "Bar"; });


We have two overloads of locked and we have to try both. The non-const overload works fine. But the const one – even if it won't be selected by overload resolution anyway – still has to be instantiated (it's a generic lambda, so to figure out what decltype(std::forward<F>(f)(m_data)) might be you have to instantiate it) and that instantiation fails within the body of the lambda. The body is outside of the immediate context, so it's not a substitution failure – it's a hard error.



When you call this:



str.locked([](std::string& s) { s = "Bar"; });


We don't need to look at the body at all during the whole process of overload resolution – we can simply reject at the call site (since you can't pass a const string into a string&).



There's not really a solution to this problem in the language today – you basically have to add constraints on your lambda to ensure that the instantiation failure happens in the immediate context of substitution rather than in the body. Something like:



str.locked([](auto &s) -> decltype(s = std::string(), void()) {
s = "Bar";
});




A more thorough language solution would have been to allow for "Deducing this" (see the section in the paper about this specific problem). But that won't be in C++20.






share|improve this answer





















  • 5





    Well this is a shame. +1 as this had me really scratching my head. I couldn't figure out why it was calling the const version, and as you point out it really isn't, it just has to check, and the check results in a hard error.

    – NathanOliver
    14 hours ago











  • Thank you for this explanation. Could you elaborate on "The body is outside of the immediate context" a bit though? (I'm unclear of what exactly is the immediate context)

    – YSC
    14 hours ago













  • Thank you for the explanation and the workaround. It works, but since it's more verbose than writing the type, I'll do that instead of using auto for this case. I'll check out the paper too.

    – Unda
    14 hours ago











  • Would it work if you took the parameter as an auto&& parameter (though then you can pass rvalues, which you don't really want to allow)?

    – Nicol Bolas
    12 hours ago








  • 1





    @Unda Yeah, if you want to call it like locked(str, []{...}) instead. Just changes the syntax.

    – Barry
    8 hours ago














19












19








19







This is a problem fundamentally with what happens with SFINAE-unfriendly callables. For more reference, check out P0826.



The problem is, when you call this:



 str.locked([](auto &s) { s = "Bar"; });


We have two overloads of locked and we have to try both. The non-const overload works fine. But the const one – even if it won't be selected by overload resolution anyway – still has to be instantiated (it's a generic lambda, so to figure out what decltype(std::forward<F>(f)(m_data)) might be you have to instantiate it) and that instantiation fails within the body of the lambda. The body is outside of the immediate context, so it's not a substitution failure – it's a hard error.



When you call this:



str.locked([](std::string& s) { s = "Bar"; });


We don't need to look at the body at all during the whole process of overload resolution – we can simply reject at the call site (since you can't pass a const string into a string&).



There's not really a solution to this problem in the language today – you basically have to add constraints on your lambda to ensure that the instantiation failure happens in the immediate context of substitution rather than in the body. Something like:



str.locked([](auto &s) -> decltype(s = std::string(), void()) {
s = "Bar";
});




A more thorough language solution would have been to allow for "Deducing this" (see the section in the paper about this specific problem). But that won't be in C++20.






share|improve this answer















This is a problem fundamentally with what happens with SFINAE-unfriendly callables. For more reference, check out P0826.



The problem is, when you call this:



 str.locked([](auto &s) { s = "Bar"; });


We have two overloads of locked and we have to try both. The non-const overload works fine. But the const one – even if it won't be selected by overload resolution anyway – still has to be instantiated (it's a generic lambda, so to figure out what decltype(std::forward<F>(f)(m_data)) might be you have to instantiate it) and that instantiation fails within the body of the lambda. The body is outside of the immediate context, so it's not a substitution failure – it's a hard error.



When you call this:



str.locked([](std::string& s) { s = "Bar"; });


We don't need to look at the body at all during the whole process of overload resolution – we can simply reject at the call site (since you can't pass a const string into a string&).



There's not really a solution to this problem in the language today – you basically have to add constraints on your lambda to ensure that the instantiation failure happens in the immediate context of substitution rather than in the body. Something like:



str.locked([](auto &s) -> decltype(s = std::string(), void()) {
s = "Bar";
});




A more thorough language solution would have been to allow for "Deducing this" (see the section in the paper about this specific problem). But that won't be in C++20.







share|improve this answer














share|improve this answer



share|improve this answer








edited 13 hours ago









Baum mit Augen

41.3k12118154




41.3k12118154










answered 14 hours ago









BarryBarry

183k21319584




183k21319584








  • 5





    Well this is a shame. +1 as this had me really scratching my head. I couldn't figure out why it was calling the const version, and as you point out it really isn't, it just has to check, and the check results in a hard error.

    – NathanOliver
    14 hours ago











  • Thank you for this explanation. Could you elaborate on "The body is outside of the immediate context" a bit though? (I'm unclear of what exactly is the immediate context)

    – YSC
    14 hours ago













  • Thank you for the explanation and the workaround. It works, but since it's more verbose than writing the type, I'll do that instead of using auto for this case. I'll check out the paper too.

    – Unda
    14 hours ago











  • Would it work if you took the parameter as an auto&& parameter (though then you can pass rvalues, which you don't really want to allow)?

    – Nicol Bolas
    12 hours ago








  • 1





    @Unda Yeah, if you want to call it like locked(str, []{...}) instead. Just changes the syntax.

    – Barry
    8 hours ago














  • 5





    Well this is a shame. +1 as this had me really scratching my head. I couldn't figure out why it was calling the const version, and as you point out it really isn't, it just has to check, and the check results in a hard error.

    – NathanOliver
    14 hours ago











  • Thank you for this explanation. Could you elaborate on "The body is outside of the immediate context" a bit though? (I'm unclear of what exactly is the immediate context)

    – YSC
    14 hours ago













  • Thank you for the explanation and the workaround. It works, but since it's more verbose than writing the type, I'll do that instead of using auto for this case. I'll check out the paper too.

    – Unda
    14 hours ago











  • Would it work if you took the parameter as an auto&& parameter (though then you can pass rvalues, which you don't really want to allow)?

    – Nicol Bolas
    12 hours ago








  • 1





    @Unda Yeah, if you want to call it like locked(str, []{...}) instead. Just changes the syntax.

    – Barry
    8 hours ago








5




5





Well this is a shame. +1 as this had me really scratching my head. I couldn't figure out why it was calling the const version, and as you point out it really isn't, it just has to check, and the check results in a hard error.

– NathanOliver
14 hours ago





Well this is a shame. +1 as this had me really scratching my head. I couldn't figure out why it was calling the const version, and as you point out it really isn't, it just has to check, and the check results in a hard error.

– NathanOliver
14 hours ago













Thank you for this explanation. Could you elaborate on "The body is outside of the immediate context" a bit though? (I'm unclear of what exactly is the immediate context)

– YSC
14 hours ago







Thank you for this explanation. Could you elaborate on "The body is outside of the immediate context" a bit though? (I'm unclear of what exactly is the immediate context)

– YSC
14 hours ago















Thank you for the explanation and the workaround. It works, but since it's more verbose than writing the type, I'll do that instead of using auto for this case. I'll check out the paper too.

– Unda
14 hours ago





Thank you for the explanation and the workaround. It works, but since it's more verbose than writing the type, I'll do that instead of using auto for this case. I'll check out the paper too.

– Unda
14 hours ago













Would it work if you took the parameter as an auto&& parameter (though then you can pass rvalues, which you don't really want to allow)?

– Nicol Bolas
12 hours ago







Would it work if you took the parameter as an auto&& parameter (though then you can pass rvalues, which you don't really want to allow)?

– Nicol Bolas
12 hours ago






1




1





@Unda Yeah, if you want to call it like locked(str, []{...}) instead. Just changes the syntax.

– Barry
8 hours ago





@Unda Yeah, if you want to call it like locked(str, []{...}) instead. Just changes the syntax.

– Barry
8 hours ago




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54947560%2fwhy-does-lambda-auto-parameter-choose-const-overload%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

is 'sed' thread safeWhat should someone know about using Python scripts in the shell?Nexenta bash script uses...

How do i solve the “ No module named 'mlxtend' ” issue on Jupyter?

Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...