?
Interview Verified
Implement std::function
As title. Without needing to consider all the minutia that the standard library uses; can use heap allocation.
As a progression, discuss the motivation for and implement function_ref (To be introduced in C++ 26).
In an actual interview, evaluate how you would decide between using these types of functions vs templates or lambdas in actual trading systems logic.
Btw I did not get personally asked this, but I remember from someone in quant. This is pretty difficult so it's definietly a gauge on how familiar candidate is with the underlying concepts.
Okay more formal problem statement:
Part 1: Implement a Simplified Function<R(Args...)>
Implement:
template <class>
class Function;
template <class R, class... Args>
class Function<R(Args...)> {
public:
Function() = default;
template <class F>
Function(F f);
Function(const Function& other);
Function(Function&& other) noexcept;
Function& operator=(Function other);
~Function();
explicit operator bool() const;
R operator()(Args... args) const;
};
Requirements
Your implementation should support:
Function<void(int)> f = [](int x) {
cout << x << "\n";
};
f(5);
It should also support copying:
Function<int(int)> f = [](int x) {
return x + 1;
};
Function<int(int)> g = f;
cout << g(10) << "\n"; // 11
And moving:
Function<void()> f = [] {
cout << "hello\n";
};
Function<void()> g = std::move(f);
g();
Constraints
You may assume:
The stored callable is copy-constructible.
Heap allocation is allowed.
Exact standard-library behavior is not required.
You should handle:
default construction
construction from callable
copy construction
move construction
copy/move assignment
destruction
empty state
invocation
For empty invocation, you may either throw, assert, or document that it is invalid.
Part 2:
Implement FunctionRef<R(Args...)>
Now implement a non-owning callable reference, similar in spirit to std::function_ref.
Unlike Function, this type should not own the callable. It should only refer to an existing callable object.
Implement:
template <class>
class FunctionRef;
template <class R, class... Args>
class FunctionRef<R(Args...)> {
public:
template <class F>
FunctionRef(F& f);
R operator()(Args... args) const;
};
Requirements
This should work:
int sum = 0;
auto add = [&](int x) {
sum += x;
};
FunctionRef<void(int)> ref = add;
ref(3);
ref(4);
cout << sum << "\n"; // 7
The implementation should not allocate.
A reasonable internal representation is:
void* obj;
R (*call)(void*, Args...);
where obj points to the original callable, and call knows how to invoke it.
Discussion Prompt
After implementing both wrappers, discuss when you would use each abstraction.
In an interactive interview, this part should focus on design judgment rather than more code.
Discuss the tradeoffs between:
Function
FunctionRef
std::function
templates
plain lambdas
virtual interfaces