Home > database >  How to pass ostream operator<< as a function in C ?
How to pass ostream operator<< as a function in C ?

Time:11-01

Is there any way I can pass an std::ostream operator<< as an argument in other function call? For example:


#include <iostream>

template <typename Visitor>
void print(Visitor v, int value)
{
    v(value);
}

int main(void)
{

    std::cout.operator<<(5); // This works

    std::cout << 5; // This works

    print(std::cout.operator<<, 5); // Error happens

    return 0;
}

The error is:

$ g   -g main.cpp -o main
main.cpp: In function ‘int main()’:
main.cpp:17:12: error: no matching function for call to ‘print(<unresolved overloaded function type>, int)’
           5);
            ^
main.cpp:4:6: note: candidate: template<class Visitor> void print(Visitor, int)
 void print(Visitor v, int value)
      ^~~~~
main.cpp:4:6: note:   template argument deduction/substitution failed:
main.cpp:17:12: note:   could not deduce template parameter "Visitor"

I know in C we can do operator overloadings like std::ostream& operator<<(std::ostream& out, something); but that's not what I aim to. Let's say I want to work with other printing functions or operators (like std::fout or printf), so I want my print function to be generic as much as possible.

CodePudding user response:

You can pass a lambda instead.

print([](int value) { std::cout << value; }, 5);
  •  Tags:  
  • c
  • Related