Nia*_*las 4 c++ lambda sfinae c++11 c++14
我有一个问题,检测通用lambda的实例化是否形成良好但不可编译,并检测它已经困扰我:
#include <functional>
class future
{
public:
int get() & { return 5; }
};
// Gets the return type of F(A), returning a not_well_formed type if not well formed
template<class F, class A> struct get_return_type
{
struct not_well_formed {};
template<class _F, class _A> static not_well_formed test(...);
template<class _F, class _A> static auto test(_F &&f) noexcept(noexcept(f(std::declval<_A>()))) -> decltype(f(std::declval<_A>()));
using type = decltype(test<F, A>(std::declval<F>()));
static constexpr bool is_noexcept = noexcept(test<F, A>(std::declval<F>()));
};
int main(void)
{
auto foo=[](auto &&x) { return x.get(); };
using type=get_return_type<decltype(foo), const future>::type;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这失败了(on clang 3.7):
ned@kate:~$ clang++-3.7 -std=c++14 -o weird_generic_lambda_thing weird_generic_lambda_thing.cpp
weird_generic_lambda_thing.cpp:21:34: error: member function 'get' not viable: 'this' argument has type 'const future', but
function is not marked const
auto foo=[](auto &&x) { return x.get(); };
^
weird_generic_lambda_thing.cpp:14:111: note: in instantiation of function template specialization 'main()::(anonymous
class)::operator()<const future>' requested here
..._F, class _A> static auto test(_F &&f) noexcept(noexcept(f(std::declval<_A>()))) -> decltype(f(std::declval<_A>()));
^
weird_generic_lambda_thing.cpp:15:25: note: while substituting explicitly-specified template arguments into function
template 'test'
using type = decltype(test<F, A>(std::declval<F>()));
^
weird_generic_lambda_thing.cpp:22:14: note: in instantiation of template class 'get_return_type<(lambda at
weird_generic_lambda_thing.cpp:21:12), const future>' requested here
using type=get_return_type<decltype(foo), const future>::type;
^
weird_generic_lambda_thing.cpp:6:7: note: 'get' declared here
int get() & { return 5; }
^
1 error generated.
Run Code Online (Sandbox Code Playgroud)
你可能会在这里责怪我对Expression SFINAE缺乏经验(感谢Visual Studio!),但我很惊讶:如果f(std::declval<_A>())形成不好,那么创建返回类型test()的decltype肯定无法替代?
显然答案是,它确实无法替代,但是以非SFINAE的方式.以上是否可以修复,如果泛型lambda与某些任意参数类型不可编译,它会正确返回not_well_formed类型?
你不能一般.只能通过SFINAE检测到早期故障.早期失败基本上是函数(或类)模板的声明,而不是定义.
lambda可以通过明确声明返回类型->decltype(x.get())或通过其他SFINAE技术(如enable_if_t或)来提供SFINAE早期故障检测void_t.
这个想法是编译器不需要完全编译函数以进行重载解析.