[英]C++ function template initialization?
我不確定這個標題是否反映了這個問題。 這是一個模板 function。 我的問題是
下面代碼中的 s(...) 是什么意思,因為編譯器不知道 class 是什么,編譯器甚至沒有抱怨。
我不太明白發生了什么事。 謝謝
template <class Something>
void foo(Something s)
{
s(0, {"--limit"}, "Limits the number of elements."); //What does this mean?
s(false, {"--all"}, "Run all");
}
看起來foo
的意圖是接受一個有call operator的 class 。
例如
#include <iostream>
#include <string>
#include <vector>
struct ReallySomething {
void operator()(bool b, const std::vector<std::string>& flags, const std::string& description)
{
std::cout << "Condition is " << (b ? "true" : "false") << std::endl;
std::cout << "Number of flags: " << flags.size() << std::endl;
std::cout << "Description: " << description << std::endl;
}
};
template <class Something>
void foo(Something s)
{
s(0, {"--limit"}, "Limits the number of elements."); //What does this mean?
s(false, {"--all"}, "Run all");
}
int main()
{
ReallySomething r;
foo(r);
return 0;
}
然后
s(false, {"--all"}, "Run all");
和
s(0, {"--limit"}, "Limits the number of elements.");
將調用此 function。
試試這里的代碼
下面代碼中的 s(...) 是什么意思
這意味着您試圖在傳遞不同的 arguments 0
, {"--limit"}
, "Limits the number of elements
的同時調用s
。例如, s
可能是某些類類型,它重載了調用運算operator()
,它采用可變數量的 arguments。
所以通過寫:
s(0, {"--limit"}, "Limits the number of elements."); //you're using the overloaded call operator() for some given class type
在上面,您使用重載調用operator()
並將不同的 arguments 傳遞給它。
讓我們看一個人為的例子:
struct Custom
{
//overload operator()
template<typename... Args>
void operator()(const Args&...args)
{
std::cout << "operator() called with: "<<sizeof...(args)<<" arguments"<<std::endl;
}
};
template <class Something>
void foo(Something s)
{
s(0, "--limit", "Limits the number of elements."); //call the overloaded operator()
s(false, "--all", "Run all", 5.5, 5); //call the overloaded operator()
}
int main()
{
Custom c; //create object of class type Custom
foo(c); //call foo by passing argument of type `Custom`
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.