myW*_*SON 4 c++ boost boost-mpl boost-preprocessor c++11
我想知道是否有可能使用boost :: mpl / preprocessor或某些noce C ++ 11功能从类类型和函数名称创建函数代理。
说我们有:
inline void set_email(const ::std::string& value);
inline void set_email(const char* value);
Run Code Online (Sandbox Code Playgroud)
内部类电子邮件。我们知道有set_email函数,我们想用API创建一个prox类,例如
PROXY(Email, set_email, MyEmail)
Email * email = new Email();
MyEmail * myEmail = new MyEmail(email);
Run Code Online (Sandbox Code Playgroud)
并且有能力调用任何set_email重载。是否有可能以及如何创建这样的类来代理任何数量的不知道那里类型(仅名称)的重载函数?
这个怎么样:
#include <type_traits>
#include <utility>
#define PROXY(proxified, member_function, proxy_name) \
class proxy_name \
{ \
private: \
proxified & ref_; \
\
public: \
proxy_name(proxified &ref) \
: ref_(ref) \
{ \
} \
\
/* general version */ \
template<typename ... Args> \
auto member_function(Args&& ... args) \
-> typename std::enable_if<!std::is_void<decltype(ref_.member_function(std::forward<Args>(args)...))>::value, \
decltype(ref_.member_function(std::forward<Args>(args)...))>::type \
{ \
return (ref_.member_function(std::forward<Args>(args)...)); \
} \
\
/* void return type version */ \
template<typename ... Args> \
auto member_function(Args&& ... args) \
-> typename std::enable_if<std::is_void<decltype(ref_.member_function(std::forward<Args>(args)...))>::value, \
void>::type \
{ \
ref_.member_function(std::forward<Args>(args)...); \
} \
\
};
Run Code Online (Sandbox Code Playgroud)
这对我来说可以编译并正常工作g++ 4.7:
#include "proxy_macro.hpp"
#include <iostream>
#include <string>
class Email
{
public:
void set_email(const ::std::string& value)
{
std::cout << value << std::endl;
}
void set_email(const char* value)
{
std::cout << value << std::endl;
}
int set_email()
{
return (42);
}
};
PROXY(Email, set_email, MyEmail)
int main(void)
{
Email mail;
MyEmail my_mail(mail);
std::string str = "test string";
const char * ptr = "test char pointer";
my_mail.set_email(str);
my_mail.set_email(ptr);
std::cout << "test return: " << my_mail.set_email() << std::endl;
return (0);
}
Run Code Online (Sandbox Code Playgroud)
#include <type_traits>
#include <utility>
#define PROXY(proxified, member_function, proxy_name) \
class proxy_name \
{ \
private: \
proxified & ref_; \
\
public: \
proxy_name(proxified &ref) \
: ref_(ref) \
{ \
} \
\
template<typename ... Args> \
auto member_function(Args&& ... args) \
-> decltype(ref_.member_function(std::forward<Args>(args)...)) \
{ \
return (ref_.member_function(std::forward<Args>(args)...)); \
} \
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
775 次 |
| 最近记录: |