类似于std::function,
#include<tuple>
template<typename T>
class Function;
template<typename T, typename... Arg>
class Function<T(Arg...)> {
public:
static const size_t size_arg = sizeof... (Arg);
using fun_point_type = T(*)(Arg...);
using return_type = T;
using args = std::tuple<Arg...>;
template<size_t N>
using arg = std::tuple_element_t<N, args>;
template<typename Ty>
constexpr Function(Ty lam): func(static_cast<fun_point_type>(lam)){
}
constexpr auto operator ()(Arg... arg) const {
if constexpr (!std::is_same_v<T, void >)
return func(arg...);
else
func(arg...);
}
private:
fun_point_type func;
};
template<typename T, typename... Arg>
Function(T(*)(Arg...))->Function<T(Arg...)>;
通过使用模板参数包装函数的返回值类型,然后使用构造函数进行构造,这里没有做过多的封装,只是想展示一下如何将一个函数对象包装到类中。
测试代码:
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
[[maybe_unused]] constexpr Function<int(char,double)>::arg<0> ty = 1.0;
auto f2 = [](auto s){
if constexpr(std::is_same_v<decltype (s), char>){
return true;
}
else
{
return false;
}
};
[[maybe_unused]]constexpr bool mi = f2(ty); //true
constexpr Function<int(int)> fun{[]([[maybe_unused]] int a){return 11;}};
[[maybe_unused]] constexpr auto i = fun(12); // i=11
return a.exec();
}