此代碼使用 gcc 和 clang 編譯:
#define PACK //...
template <typename Result, typename PACK Args, typename Last>
auto g(Result (*f)(Args PACK, Last)) -> Result (*)(Args PACK)
{
return reinterpret_cast<Result (*)(Args PACK)>(f);
}
double af(char c, int i);
auto ag{g(&af)};
但是,如果我將第一行更改為:
#define PACK ...
兩個編譯器都不會接受它。該錯誤表示模板型別引數檢測失敗。為什么可以檢測到單個型別,但不能檢測到(退化的)包?
(一些背景知識:我正在使用一個應用程式,該應用程式利用以下事實:使用重新解釋強制轉換,如果函式的引數型別是引數型別的前綴,典型的 ABI 保證將函式地址分配給函式指標是安全的指向函式型別,并且回傳型別匹配。我試圖撰寫一個靜態檢查這種情況的模板。)
uj5u.com熱心網友回復:
第二種情況的正確語法如下所示。注意Last和的順序Args...是如何改變的。
方法一
//----------------------------------------------------vvvv--->OK: Last is deducible
template <typename Result, typename... Args, typename Last>
auto g(Result (*f)(Last, Args...)) -> Result (*)(Args...)
//-----------------------^^^^------------------------------>order changed here
{
return reinterpret_cast<Result (*)(Args...)>(f);
}
int func(int, float, double, char, bool);
auto ptr = g(&func);
演示
方法二
//---------------------------------vvvv--------------------->Last comes before Args though this is not necessary here as it is deducible as shown in method 1 above
template <typename Result,typename Last, typename... Args>
auto g(Result (*f)(Last, Args...)) -> Result (*)(Args...)
//-----------------------^^^^------------------------------>order changed here
{
return reinterpret_cast<Result (*)(Args...)>(f);
}
int func(int, float, double, char, bool);
auto ptr = g(&func);
演示
uj5u.com熱心網友回復:
正如康桓瑋在對該問題的評論中指出的那樣,引數包只允許在函式的形式引數串列的末尾。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489109.html
上一篇:臨時繼承中忽略的虛方法
