Channel Directions in C++

#include <iostream>
#include <string>
#include <queue>
#include <thread>

// This `ping` function only accepts a queue for sending
// values. It's not possible to receive from this queue.
void ping(std::queue<std::string>& pings, const std::string& msg) {
    pings.push(msg);
}

// The `pong` function accepts one queue for receives
// (`pings`) and a second for sends (`pongs`).
void pong(std::queue<std::string>& pings, std::queue<std::string>& pongs) {
    std::string msg = pings.front();
    pings.pop();
    pongs.push(msg);
}

int main() {
    std::queue<std::string> pings;
    std::queue<std::string> pongs;

    ping(pings, "passed message");
    pong(pings, pongs);
    
    std::cout << pongs.front() << std::endl;
    
    return 0;
}

When using queues as function parameters in C++, you can specify if a queue is meant to only send or receive values. This specificity increases the type-safety of the program.

The ping function only accepts a queue for sending values. It’s not possible to receive from this queue within the function.

The pong function accepts one queue for receives (pings) and a second for sends (pongs).

In the main function, we create two queues, pings and pongs. We then call ping to send a message, pong to receive from pings and send to pongs, and finally print the received message.

To compile and run this program:

$ g++ -std=c++11 channel_directions.cpp -o channel_directions
$ ./channel_directions
passed message

Note that C++ doesn’t have built-in channels like Go does. In this example, we’ve used std::queue as a simple substitute. For more complex scenarios involving concurrent access, you might want to use thread-safe queues or other synchronization primitives.