How to inspect the type of argument that function A will call passed in function B with in C++ 14

Viewed 73

I have the following code.

#include <utility>
#include <iostream>
#include <vector>


int main () {

    // A function that when passed another
    // function will call it with a value.
    // In this case tap calls out with (int)10. 
    auto tap = [](auto out){
        out(10);     
    };

    // A function that when passed a tap shaped function will
    // collect all values from the tap and
    // add them to the vector.
    auto toVector = [](auto && tap){
        using T = int;
        std::vector<T> out;
        tap([&](auto const & i){ out.push_back(i);});
        return out;
    };
 

    // Using generic toVector collect all results from the specific ``tap`` function above
    auto vec = toVector(tap);

    std::cerr << vec[0] << std::endl;
}

The problem with the above is that toVector is not generic. I need the line

using T = int

to make it work.

Is it possible to change toVector to be fully generic by something like

    // A function that when passed a tap will
    // collect all values from the tap and
    // add them to the vector.
    auto toVector = [](auto && tap){
        using T = Tap<tap>::type;
        std::vector<T> out;
        tap([&](auto const & i){ out.push_back(i);});
        return out;
    };

where Tap<T>::type is the magic meta function yet to be discovered.

0 Answers
Related