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

Why do neural networks need so many training examples to perform?

Can I write a book of my D&D game?

Why did other German political parties disband so fast when Hitler was appointed chancellor?

We are very unlucky in my court

Why are the books in the Game of Thrones citadel library shelved spine inwards?

How to deal with an incendiary email that was recalled

Would a National Army of mercenaries be a feasible idea?

Caruana vs Carlsen game 10 (WCC) why not 18...Nxb6?

Indirectly access environment variable

What is the most triangles you can make from a capital "H" and 3 straight lines?

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?

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

Avoiding morning and evening handshakes

Program that converts a number to a letter of the alphabet

Dilemma of explaining to interviewer that he is the reason for declining second interview

Why is "points exist" not an axiom in geometry?

What makes the Forgotten Realms "forgotten"?

Why would the Pakistan airspace closure cancel flights not headed to Pakistan itself?

How do you funnel food off a cutting board?

Cookies - Should the toggles be on?

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

What to do when being responsible for data protection in your lab, yet advice is ignored?

Every character has a name

Is there a standard way to treat events with unknown times (missing time data)?



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













10















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
    1 hour ago













  • @YSC the call operator is templated, but not the lambda itself, is it ? So why should I declare F as a template ?

    – Unda
    1 hour ago
















10















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
    1 hour ago













  • @YSC the call operator is templated, but not the lambda itself, is it ? So why should I declare F as a template ?

    – Unda
    1 hour ago














10












10








10


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 2 hours ago









UndaUnda

1,18531926




1,18531926













  • @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
    1 hour ago













  • @YSC the call operator is templated, but not the lambda itself, is it ? So why should I declare F as a template ?

    – Unda
    1 hour 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
    1 hour ago













  • @YSC the call operator is templated, but not the lambda itself, is it ? So why should I declare F as a template ?

    – Unda
    1 hour 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
1 hour 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
1 hour ago















@YSC the call operator is templated, but not the lambda itself, is it ? So why should I declare F as a template ?

– Unda
1 hour ago





@YSC the call operator is templated, but not the lambda itself, is it ? So why should I declare F as a template ?

– Unda
1 hour ago












1 Answer
1






active

oldest

votes


















13














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





















  • 4





    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
    1 hour 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
    1 hour 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
    1 hour 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









13














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





















  • 4





    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
    1 hour 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
    1 hour 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
    1 hour ago
















13














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





















  • 4





    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
    1 hour 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
    1 hour 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
    1 hour ago














13












13








13







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 29 mins ago









Baum mit Augen

41.3k12118154




41.3k12118154










answered 1 hour ago









BarryBarry

183k20318584




183k20318584








  • 4





    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
    1 hour 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
    1 hour 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
    1 hour ago














  • 4





    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
    1 hour 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
    1 hour 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
    1 hour ago








4




4





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
1 hour 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
1 hour 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
1 hour 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
1 hour 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
1 hour 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
1 hour 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

“%fieldName is a required field.”, in Magento2 REST API Call for GET Method Type The Next...

How to change City field to a dropdown in Checkout step Magento 2Magento 2 : How to change UI field(s)...

夢乃愛華...