前回に補足。
前回の例で、色々な型を返す関数がオブジェクトのメンバ関数だった場合、前回のケースでは上手く行かない。
そこで、メンバ関数バージョン。
sample_membfuncs.cpp
# include <string>
# include <iostream>
std::string get_functype(int) {
return "You have returned an int value.";
}
std::string get_functype(double) {
return "You have returned a double value.";
}
std::string get_functype(void) {
return "You have returned nothing.";
}
class MyClass {
public:
int int_func(int n1, int n2) {
auto ret = n1 + n2;
std::cout << "I will return " << ret << "." << std::endl;
return ret;
}
double double_func(double ret) {
std::cout << "I will return " << ret << "." << std::endl;
return ret;
}
void void_func(void) {
std::cout << "I will return nothing." << std::endl;
}
};
template<typename RET>
struct get_functype_switch_helper {
template<typename CLS, typename... ARGS>
static auto x(CLS &obj, RET(CLS::*func)(ARGS...), ARGS... args) {
return get_functype((obj.*func)(args...));
}
};
template<>
struct get_functype_switch_helper<void> {
template<typename CLS, typename... ARGS>
static auto x(CLS &obj, void(CLS::*func)(ARGS...), ARGS... args) {
(obj.*func)(args...);
return get_functype();
}
};
template<typename CLS, typename FUNC, typename... ARGS>
inline auto get_functype_switch(CLS &obj, FUNC func, ARGS... args) {
return get_functype_switch_helper<decltype((obj.*func)(args...))>::template x<CLS, ARGS...>(obj, func, args...);
}
int main(void) {
MyClass obj;
std::cout << get_functype_switch(obj, &MyClass::int_func, 30, 70) << std::endl;
std::cout << get_functype_switch(obj, &MyClass::double_func, 3.14) << std::endl;
std::cout << get_functype_switch(obj, &MyClass::void_func) << std::endl;
return 0;
}
メンバ関数ポインタにしないといけませんでした。
以上。