c++ - 如何用不同数量的默认参数包装一个函数,使其只有一个参数?

标签 c++ c++11 templates c++14 default-arguments

我有一个模板函数,我们称之为“客户端”:

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/

相关文章:

c++ - 对带有可变参数模板的 std::ref() 和 std::bind() 有点模糊

c++ - 根据类创建时的模板参数更改类 API

c++ - 减少非虚拟多态类中基派生委托(delegate)的样板

function - std::function 可以接受仿函数吗?

c++ - C/C++ 中 void main 和 int main 的区别?

c++ - 使用 CoInitializeEx 分配 HRESULT 时出现问题

c# - 在 C# 中调用 C++ dll 时找不到入口点

C++ 入门 1.4.4。不能完全理解第一个 IF 语句的需要

c++ - 如何在 C++ 中使用模板函数实现父类?

c++ - OpenCV:convertTo 返回白色图像(有时)