2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

voidを返す関数も対等に扱いたい。 ―メンバ関数篇―

Last updated at Posted at 2014-10-17

前回に補足。

前回の例で、色々な型を返す関数がオブジェクトのメンバ関数だった場合、前回のケースでは上手く行かない。

そこで、メンバ関数バージョン。

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;
}

メンバ関数ポインタにしないといけませんでした。

以上。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?