2017-08-24 12 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