Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

C++: Is there a way to call an operator function through a static method in this context?

This is the code I have. It compiles; but I want to call the function h with the arguments of H<T>::operator(). How would I do that?

    #include <utility>

    #include <iostream>

    template <template <class> class H, typename F>

    struct N {

        N() = delete;

        static F f() {

            H<F> h;

            return h();

        }

    };

    template <class T>

    struct H {

        H() = default;

        T operator()() {

            return T();

        }

    };

    template <template <class> class T>

    int h() {

        return N<T, decltype( std::declval<T<int>>().operator()() )>::f();

    }

    int main() {

        std::cout << h<H>();

    }

For example, instead of doing h<H>() I do h<H>(5) and it outputs 5 for me through H<int>::operator(). And that also means calling the static member function f with those arguments. Can someone propose an example in which this is possible? Thanks.

1 Answer

Relevance
  • ?
    Lv 7
    8 years ago
    Favorite Answer

    I am not sure I follow, are you looking for something like this:

    #include <utility>

    #include <iostream>

    template <template <class> class H, typename F>

    struct N {

         N() = delete;

         static F f(const F& val = F()) {

              H<F> h;

              return h(val);

         }

    };

    template <class T>

    struct H {

         H() = default;

         T operator()(const T& val = T()) {

              return val;

         }

    };

    template <template <class> class T>

    int h(int val = 0) {

         return N<T, decltype( std::declval<T<int>>().operator()() )>::f(val);

    }

    int main() {

         std::cout << h<H>() << h<H>(5) << '\n';

    }

    Or do you want to pass multiple arguments to h(), forward them to f(), and use them in the constructor of H's template parameter type you hardcoded as int? That shouldn't be a problem either, but it would be nice to have a testcase.

Still have questions? Get your answers by asking now.