[英]different ways to define a function as template argument explitcly passed or not
讓:
int id(int x) { return x; }
以下代碼可通過GCC進行編譯:
template <typename F> int f2(F f, int x) { return f(x); }
int id2(int x) { return f2(id, x); }
但是以下內容無法編譯:
template <typename F> int f1(int x) { return F(x); }
int id1(int x) { return f1<id>(x); }
有人可以解釋一下這是怎么回事嗎?
它不會編譯,因為類型名typename F
需要一個類型,而您正在給它一個函數,例如int(*F)(int)
這是一個非類型模板參數。
int id(int x) { return x; }
template <int(*F)(int)> // here
int f1(int x) { return F(x); }
int id1(int x) { return f1<id>(x); }
這可以使用C ++ 17進一步簡化並變得更通用:
template <auto F>
int f1(int x) { return F(x); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.