[英]C++20 non-type template parameter which is template in the prior type parameters: is not a valid template arg, because is not a variable
[英]C++20 lambdas with non type template parameters
我在弄亂新的 C++20 lambda,似乎我可以聲明一個 lambda 接受一個非類型模板參數,但是我無法調用它。
#include <iostream>
int main() {
// compiles fine
auto f = []<bool ok>() { return ok; };
// it even has an address??
std::cout << &f;
// f(); // error : no matching function for call to object of typ
// f<true>(); // error : invalid operands to binary expression
f.operator()<true>(); // compiles but somewhat... ugly
}
我在這里查看了相關論文,但它似乎沒有提到這種情況下的調用語法。
是否禁止在 lambda 呼叫站點明確傳遞模板 arguments? 這將是一個令人失望的限制,因為我認為這樣做的目的是讓 lambda 能夠像模板一樣做很多事情。
是否禁止在 lambda 呼叫站點明確傳遞模板 arguments?
不,但問題是您沒有為正確的實體指定模板參數。 請注意, f
本身不是模板。 它是一個非模板類型的 object,它包含一個模板化的成員operator()
。
所以當你這樣做時:
f<true>(); // error
您正在為f
指定模板參數,但由於f
不是模板,您會收到錯誤消息。
另一方面,正如您所觀察到的,這個調用:
f.operator()<true>(); // ok
很好,因為您正在為f
的operator()
指定模板參數,這確實是一個模板。
此外,此問題與 lambda 的非類型模板參數無關,如果它也是類型模板參數,也會發生同樣的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.