I'd like to be able to define a function that takes an interface, but can be fulfilled with a delegate or function that provide the same functionality. For example, in C++ I can write something like:
typedef std::function<int (float)> toInt;
void fun(toInt dg) { ... }
struct impl1 {
int operator()(float x) { ... }
};
int impl2(float x) { ... }
And then call it using either implementation:
fun(impl1());
fun(&impl2);
(This float->int conversion is just a simplified example to illustrate the principle, not my actual functionality).
I'd like to achieve something similar in D. My naive attempt went like this:
interface toInt {
int opCall(float);
}
void fun(toInt dg) { ... }
int impl2(float x) { ... }
fun(impl2);
The compiler complains on this last line that it cannot implicitly convert impl2 to toInt type. I can probably just add an overloaded implementation of fun and make the conversion explicit, but I was wondering if there was a more elegant and general way of doing this, as in the C++ example above.