【发布时间】:2014-08-25 07:03:19
【问题描述】:
C++ 的可变参数模板很强大,但是很难写出这样的代码。我的问题来了:如何通过模板传递Class(见下面的代码sn-p)的构造?
注意:因为我想得到一个通用的解决方案,所以构造的参数必须是可变参数。此外,我想设置每个参数的默认值。
谁能帮帮我?
#include <iostream>
#include <utility>
template< typename R, typename C, typename... Args>
class delegate
{
public:
template<R(C::*F)(Args...)>
struct adapter
{
static R invoke_no_fwd(Args... args)
{
C t; // how to pass the construction function of C through template??? and set default value for each argument
return (t.*F)(args...);
}
};
};
class Class
{
public:
Class(int param)
: m_val(param)
{}
void print(int v)
{
std::cout << "Class: " << v + m_val << std::endl;
}
private:
int m_val;
};
int main(int argc, char** argv)
{
using namespace std;
// because the below code doesn't contain construction info, so it won't compile
typedef void(*function_t)(int);
function_t ptrFunc = (delegate<void, Class, int>::adapter<&Class::print>::invoke_no_fwd);
auto type = (delegate<void, Class, int>::adapter<&Class::print>::invoke_no_fwd);
cout << typeid(type).name() << endl;
return 0;
}
【问题讨论】:
-
你为什么不使用
std::function?你愿意接受,还是真的想自己重写所有内容? -
@quantdev 不,我想编写一个适配器,可以将非静态成员函数转换为 c 风格的函数指针。我的目的是让开发 MFC 更方便。现有的 API 接口无法更改。这是微软的秘密
-
但是
std::function也可以转换成C风格的函数ptr... -
@quantdev,绝对不是。看看这个:stackoverflow.com/questions/18370396/…
-
你说的是 c 风格的可变参数函数,然后是
printf。
标签: c++ visual-studio templates design-patterns