Why does lambda auto& parameter choose const overload?C++ error in ios_base.hWhy does changing 0.1f to 0...
What is the most triangles you can make from a capital "H" and 3 straight lines?
Why does lambda auto& parameter choose const overload?
Is there any differences between "Gucken" and "Schauen"?
How to prevent cleaner from hanging my lock screen in Ubuntu 16.04
Injecting creativity into a cookbook
Word or phrase for showing great skill at something without formal training in it
Does Improved Divine Strike trigger when a paladin makes an unarmed strike?
Slow moving projectiles from a hand-held weapon - how do they reach the target?
Strange Sign on Lab Door
Can an insurance company drop you after receiving a bill and refusing to pay?
What is the wife of a henpecked husband called?
Why did other German political parties disband so fast when Hitler was appointed chancellor?
Why Normality assumption in linear regression
Does Windows 10's telemetry include sending *.doc files if Word crashed?
Early credit roll before the end of the film
Why do stocks necessarily drop during a recession?
Breaking a Loop in Tikz
Is there some relative to Dutch word "kijken" in German?
How to avoid being sexist when trying to employ someone to function in a very sexist environment?
How to deal with an incendiary email that was recalled
My cat mixes up the floors in my building. How can I help him?
Am I a Rude Number?
How to explain planetary rings pulsating?
How can I install sudo without using su?
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
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
add a comment |
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
@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
2 hours ago
@YSC the call operator is templated, but not the lambda itself, is it ? So why should I declareF
as a template ?
– Unda
2 hours ago
add a comment |
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
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
c++ templates c++14 generic-lambda
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
2 hours ago
@YSC the call operator is templated, but not the lambda itself, is it ? So why should I declareF
as a template ?
– Unda
2 hours ago
add a comment |
@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
2 hours ago
@YSC the call operator is templated, but not the lambda itself, is it ? So why should I declareF
as a template ?
– Unda
2 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
2 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
2 hours ago
@YSC the call operator is templated, but not the lambda itself, is it ? So why should I declare
F
as a template ?– Unda
2 hours ago
@YSC the call operator is templated, but not the lambda itself, is it ? So why should I declare
F
as a template ?– Unda
2 hours ago
add a comment |
1 Answer
1
active
oldest
votes
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.
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 usingauto
for this case. I'll check out the paper too.
– Unda
1 hour ago
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
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 usingauto
for this case. I'll check out the paper too.
– Unda
1 hour ago
add a comment |
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.
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 usingauto
for this case. I'll check out the paper too.
– Unda
1 hour ago
add a comment |
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.
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.
edited 43 mins ago
Baum mit Augen
41.3k12118154
41.3k12118154
answered 2 hours 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 usingauto
for this case. I'll check out the paper too.
– Unda
1 hour ago
add a comment |
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 usingauto
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
@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
2 hours ago
@YSC the call operator is templated, but not the lambda itself, is it ? So why should I declare
F
as a template ?– Unda
2 hours ago