2017-08-24 34 views
6

我在尝试调用lambda内部的成员函数以捕获this时遇到问题。这个函数有一个常量和非常量版本,它被模板化为一个类型。模糊调用成员函数以在lambda中捕获此数据

下面的代码演示了错误:

struct TEST 
{ 
    template <typename T> 
    void test() {} 

    template <typename T> 
    void test() const {} 

    TEST() 
    { 
    [this]() 
    { 
     test<void>(); 
    }(); 
    } 
}; 

消息:http://rextester.com/MLU2098

source_file.cpp(13): error C2668: 'TEST::test': ambiguous call to overloaded function 
source_file.cpp(7): note: could be 'void TEST::test<void>(void) const' 
source_file.cpp(4): note: or  'void TEST::test<void>(void)' 
source_file.cpp(13): note: while trying to match the argument list '()' 
Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x64 

我不知道,如果这种行为是正确的,只是微软编译器的问题,所以我测试gcc和clang在编译器资源管理器中的代码,它们都编译时没有错误。

哪个编译器在此显示正确的行为?

+2

[这里有一个MSVC的摄制](http://rextester.com/MLU2098) – AndyG

回答

6

这是MSVC的问题。隐含的this参数具有cv资格。这就是为什么在cv-qualifier上重载成员函数是可能的原因。在c'tor的主体中,this指向一个非const对象(初始化意味着我们必须修改对象)。

这足以确定要调用的重载。

无论出于何种原因,MSVC都很困惑。但是,如果你通过明确访问this指针调用成员函数,混乱消失:

void bar() 
{ 
    [this]() 
    { 
    this->test<void>(); 
    }(); 
} 

Live MSVC Example