[英]Use default parameter for templated function
I have two functions which look very similar to me :我有两个与我非常相似的函数:
template <typename Predicate>
vector<int> FindTopItems(const string& query,
const Predicate& predicate) const;
vector<int> FindTopItems(const string& query,
ItemStatus status = ItemStatus::Initial) const;
It is possible to use only templated version of this function?可以只使用这个函数的模板版本吗? How to set it's predicate to default value, set by enum class?如何将它的谓词设置为默认值,由枚举类设置?
So I want the following code to be compilable :所以我希望以下代码是可编译的:
int main() {
FindTopItems(""s, [](){}); /* predicate version */
FindTopItems(""s); /* default parameter as enum class should be used */
return 0;
}
You can set the default value for predicate to ItemStatus
, then make a helper class that returns your default value.您可以将 predicate 的默认值设置为ItemStatus
,然后创建一个返回默认值的辅助类。
#include <iostream>
#include <vector>
#include <string>
enum class ItemStatus {
Initial
};
template <typename T>
auto defaultValue() {
return T{};
}
template <>
auto defaultValue<ItemStatus>() {
return ItemStatus::Initial;
}
template <typename Predicate = ItemStatus>
std::vector<int> FindTopItems(const std::string& query, const Predicate& predicate = defaultValue<Predicate>()) {
if constexpr (std::is_same_v<Predicate, ItemStatus>) {
std::cout << "ItemStatus " << static_cast<int>(predicate) << '\n';
} else {
std::cout << "Predicate " << predicate() << '\n';
}
return {};
}
int main() {
FindTopItems(std::string{}, [](){ return 1; }); /* predicate version */
FindTopItems(std::string{}); /* default parameter as enum class should be used */
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.