我有一个模板函数,我们称之为“客户端”:
template<typename T>
void client(T (*func)(const std::string&), const std::string& s) {}
然后有许多“adaptee”函数都具有相同类型的第一个非默认参数,但以下参数的数量不同并且具有默认值:
void adaptee_one(const std::string&, int i = 1, char* c = nullptr) {}
void adaptee_two(const std::string&, float* f = nullptr) {}
上述功能是给定的。现在我要做的是将它们传递给上面的client<>()
函数作为第一个参数,我只关心传递第一个参数,const std::string&
.所以我做了以下事情:
void bindAdapteeOne(const std::string& s) {
return adaptee_one(s);
}
void bindAdapteeTwo(const std::string& s) {
return adaptee_two(s);
}
然后通过bindAdapteeX()
至client<>()
.
我想做的是自动化包装或使用一个(模板化的)包装器,而不是每个适配者一个。我觉得可变参数可能就是这种情况,但对如何准确应用它们知之甚少。
C++11 很好,如果绝对必要,C++14 也很好。
最佳答案
C++11 is fine, C++14 is fine if absolutely necessary.
这里是 C++11 解决方案。
What I'd like to do is to automate the wrapping or have one (templated) wrapper instead of one per adaptee.
我不会那样做。您可以简单地使用非捕获 lambda 并让它们衰减为函数指针:
client (+[](const std::string& s) { return adaptee_one(s); }, "foo");
我不认为将它们包装在模板或其他东西中会给您提供更具可读性或易于使用的解决方案。
作为一个最小的工作示例:
#include<string>
template<typename T>
void client(T (*func)(const std::string&), const std::string& s) {}
void adaptee_one(const std::string&, int i = 1, char* c = nullptr) {}
void adaptee_two(const std::string&, float* f = nullptr) {}
int main() {
client (+[](const std::string& s) { return adaptee_one(s); }, "foo");
}
关于c++ - 如何用不同数量的默认参数包装一个函数,使其只有一个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44955393/