Reputation: 172
I have a function that behaves almost the same whether I do a call to read(...) or write(...) that handles transfers to and from a file descriptor. I want to write a function like this:
uint32_t handleTX(ssize_t (*func)(int, void *, size_t));
I also have two functions:
uint32_t myRead() { return handleTX(::read); }
uint32_t myWrite() { return handleTX(::write); }
This is using the functions declared in unistd.h. The problem with this is that write(...) uses a 'const void *buf' whereas read(...) uses a 'void *buf'. Thus the two function signatures don't match. Is there a way I can cast the function signature to something to make them match? I thought about casting the function pointer to a (void *), but it doesn't seem the most elegant. Alternatively, I could make handleTX(...) a macro, but again it's not very clean. Any other suggestions?
Upvotes: 0
Views: 427
Reputation: 1
template uint32_t handleTX(Function f) { ... do whatever you need n = f(fd, data, size); }
uint32_t myRead() { return handleTX(::read); } uint32_t myWrite() { return handleTX(::write); }
Upvotes: -1
Reputation: 1901
This is highly improper to have a universal signature like that. These functions do completely different things and do different interpretation of the parameter. Getting rid of const isn't the correct approach.
If your goal is to be transparent for the function and simply add your own prefix-postfix things around the given function, the simplest method is to do:
template <class Function>
uint32_t handleTX(Function f)
{
... do whatever you need
n = f(fd, data, size);
}
uint32_t myRead() { return handleTX(::read); }
uint32_t myWrite() { return handleTX(::write); }
Whether it will work depends on whether 'data' is always mutable. This will match both.
Upvotes: 2
Reputation: 1105
As John Zwinck said, you can use a wrapper for write()
alone, or you could implement wrapper for both read()
and write()
to completely abstract read()
and write()
from unistd.h
Instead of function pointers, you could have used enum's to differentiate read()
and write()
operation by handleTX()
Upvotes: 0
Reputation: 249093
Write your own trivial wrapper for write()
which takes a non-const data pointer. Then you can pass that to handleTX()
.
Upvotes: 0