2014-11-05 26 views
4

下面的代碼在使用GCC和Clang使用C++ 11模式構建時無需編譯錯誤/警告。但是,如果我嘗試編譯沒有C++ 11模式,並在第二個範圍發生錯誤。本地類作爲謂詞pre C++ 11

#include <algorithm> 
#include <vector> 

struct astruct 
{ 
    int v; 
}; 

struct astruct_cmp0 
{ 
    bool operator()(const astruct& a0, const astruct& a1) { 
    return a0.v < a1.v; 
    } 
}; 

int main() 
{ 
    std::vector<astruct> alist; 
    { 
     // Works - no errors 
     std::stable_sort(alist.begin(),alist.end(),astruct_cmp0()); 
    } 

    { 
     struct astruct_cmp1 
     { 
     bool operator()(const astruct& a0, const astruct& a1) { 
      return a0.v < a1.v; 
     } 
     }; 

     // error: template argument uses local type 'astruct_cmp1' 
     std::stable_sort(alist.begin(),alist.end(),astruct_cmp1()); 
    } 

    return 0; 
} 

我的問題是:什麼是C++ 11的變化,允許本地結構定義?有人可以請我指向標準中的特定部分(可能是9.8節?)

回答

6

在C++ 03函數中,本地類型不是可行的模板參數。在C++ 11函數中,本地類型是可行的模板參數。在C++ 03的關鍵報價14.3.1 [temp.arg.type]段2:

以下類型不應被用作模板參數的一個模板類型參數:

  • 類型,其名字沒有聯動
  • ...

在C++ 11這個約束被刪除。

聯動定義爲當上的相關部分爲3.5 [basic.link](在這兩個標準),這是相當長的,並指向實體不聯動由排斥,第8段中C++ 03:

這些規則未涵蓋的名稱沒有鏈接。 ...

函數中定義的類型未在「這些規則」中列出。