Overloaded function as argument of variadic template function

后端 未结 2 1188
小蘑菇
小蘑菇 2021-01-12 12:02

I\'m trying to make variadic template function, which takes as arguments overloaded function and its arguments :)

int sumall(int a) { return a; }
int sumall(         


        
2条回答
  •  孤街浪徒
    2021-01-12 13:05

    When taking a pointer of a function the compiler needs to know which of the overloads you want to use. There is no way to pass a pointer to an "overload set" and have the compiler decide later. Neither of you examples works with any of the compilers I tried (very recent versions of EDG, gcc, and clang).

    I don't think you can do what you want without changing the notation of your call. If you are willing to change the call you can encapsulate the knowledge about the function to be called into a class, e.g.:

    struct sumall_t {
        template 
        auto operator()(T... args) -> decltype(sumall(args...)) {
            return sumall(args...);
        }
    };
    

    This effectively creates a wrapper for an overload set. Since the result type can't be deduced directly and may depend on how the function is called, you'd need to use a different version of doit() as well:

    template
    auto doit( Func f, A... a) ->decltype(f(a...)) {
        return f(a...);
    }
    

    This would then be used something like this:

    doit(sumall_t(), 1, 2);
    

    Another way to fix this is to mandate specification of the result type: in some way you try to do two things at once: you want to deduce the result type of the function to be called and you want to guide the compiler to choose a specific overload of a result set. However, these are interdependent. If you remove any dependency on deducing any template from the function pointer, you don't need wrap the overload set because you can determine the choice of overloaded function from the first argument to the function. In case you claim that "my compiler can do it if the return type isn't void" I'd say that your compiler is actually wrong in doing this.

提交回复
热议问题