0

使用Microsoft Visual Studio 2012,我嘗試編譯如下:讓函數指針模板參數接受右值引用是否合法?

template <void (*f)(int && y)> 
void foo() {} 

,並得到這個錯誤:

error C2993: 'int &&' : illegal type for non-type template parameter 'y' 

那真的是非法的?或者這是MSVS中的錯誤?如果是這樣,有沒有人知道它是否能在更高版本中使用?

+3

這裏沒什麼不合法的。可能是因爲函數指針類型的第一個參數名稱爲'y',MSVC會感到困惑,在這裏這不是必需的。嘗試'template '。 – jrok 2014-10-29 13:40:15

+3

在VS2013中起作用。 – 2014-10-29 13:44:53

+0

對於G ++,您必須添加-std = C++ 0x作爲編譯器選項,否則它將不會被解析。 – SCFrench 2014-10-29 17:49:38

回答

1

這實際上是VS2012編譯器中的一個拒絕有效的錯誤,它被函數類型中的參數名稱弄糊塗,認爲函數類型的參數是模板參數,因此是投訴。 C++ 11模式下的G ++ 4.8和4.9接受此代碼,Clang 3.3和ICC 13也如此;這是使用Godbolt's interactive compiler進行檢查的。另外,作爲每N3337 14.1(temp.param)P4,指針和到功能左值的引用,而不限制所允許的功能參數或返回類型:

A non-type template-parameter shall have one of the following (optionally cv-qualified) types:

  • integral or enumeration type,
  • pointer to object or pointer to function,
  • lvalue reference to object or lvalue reference to function,
  • pointer to member,
  • std::nullptr_t .

解決方法是如在評論中提到羅:簡單地去掉函數類型的參數名稱 - 我能夠測試的所有編譯器都接受這一點。