Function argument returning void or non-void type

后端 未结 4 1067
心在旅途
心在旅途 2021-01-17 10:37

I am in the middle of writing some generic code for a future library. I came across the following problem inside a template function. Consider the code below:



        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-17 11:17

    Some specialization, somewhere, is necessary. But the goal here is to avoid specializing the function itself. However, you can specialize a helper class.

    Tested with gcc 9.1 with -std=c++17.

    #include 
    #include 
    
    template
    struct return_value {
    
    
        T val;
    
        template
        return_value(F &&f, Args && ...args)
            : val{f(std::forward(args)...)}
        {
        }
    
        T value() const
        {
            return val;
        }
    };
    
    template<>
    struct return_value {
    
        template
        return_value(F &&f, Args && ...args)
        {
            f(std::forward(args)...);
        }
    
        void value() const
        {
        }
    };
    
    template
    auto foo(F &&f)
    {
        return_value()(2, 4))> r{f, 2, 4};
    
        // Something
    
        return r.value();
    }
    
    int main()
    {
        foo( [](int a, int b) { return; });
    
        std::cout << foo( [](int a, int b) { return a+b; }) << std::endl;
    }
    

提交回复
热议问题