//
#ifndef COMMCOMMAND_H
#define COMMCOMMAND_H
#include<functional>
#include<type_traits>
template <typename R = void>
class CommCommand
{
private:
std::function<R()> m_f;
public:
//接受可调用对象的函数包装器
template<class F,class ... Args,class = typename std::enable_if<!std::is_member_function_pointer<F>::value>::type>
void Wrap(F &&f, Args &&...args)
{
m_f = [&] {return f(args...); };
}
//接受常量成员函数的函数包装器
template<class E,class C,class... DArgs,class P,class ... Args>
void Wrap(E(C::*f)(DArgs...) const, P && p, Args &&... args)
{
m_f = [&, f] {return (*p.*f)(args...); };
}
//接受非常量成员函数的函数包装器
template<class E, class C, class... DArgs, class P, class ... Args>
void Wrap(E(C::*f)(DArgs...) , P && p, Args &&... args)
{
m_f = [&, f] {return (*p.*f)(args...); };
}
R Execute()
{
return m_f();
}
};
#endif // !COMMCOMMAND_H
// exerciseC11.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include "CommCommand.h"
class A
{
public:
void hello1(std::string x)
{
std::cout << x << std::endl;
}
void hello()
{
std::cout << "hello" << std::endl;
}
};
void hello()
{
std::cout << "hello" << std::endl;
}
void hello1(std::string x)
{
std::cout << x << std::endl;
}
int main()
{
CommCommand<void> cmd;
cmd.Wrap(hello);
cmd.Execute();
cmd.Wrap(hello1, "hahaha");
cmd.Execute();
A a;
//cmd.Wrap(&A::hello1, &a,"hi");
cmd.Wrap(&A::hello, &a);
cmd.Execute();
return 0;
}