I want to create a smart pointer that in case it have a function (static, lambda or member function) it can be called using "operator()", this is my first approach:
#include <cstdio>
#include <type_traits>
#include <iostream>
#include <string>
using namespace std;
template <typename Class>
struct TestPtrImpl {
Class* ptr;
TestPtrImpl(Class* ptr) : ptr(ptr) { }
template <typename... Args>
inline auto operator()(Args... args) {
if (ptr) {
if constexpr (std::is_invocable<Class, Args...>::value) {
return ptr(args...);
}
}
}
};
template <typename TClass>
TestPtrImpl<TClass> TestPtr(TClass* ptr) { return TestPtrImpl<TClass>(ptr); }
int test(string b, int a = 3) {
cout << "Hello World" << b << a << endl;
return 0;
}
int main() {
cout << TestPtr(test)("h",5) << endl;
return 0;
}
But when I try to call TestPtr(test) with only the string parameter it doesn't call the function (so default parameters seems to not work with "std::is_invocable", is there any other solution that can be used in any function case?
And, Is there an implementation of "->" that can be safe-called (like for example null conditional "?" operator in C#)?