C++代码片段(一)萃取函数返回值类型,参数类型,参数个数
生活随笔
收集整理的這篇文章主要介紹了
C++代码片段(一)萃取函数返回值类型,参数类型,参数个数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
函數(shù)的類型主要集中在以下幾種
- 函數(shù)指針
- 函數(shù)對象,是一個類對象,內(nèi)部重載的operator()函數(shù)是一個函數(shù)指針
- lambda,匿名函數(shù)對象,同函數(shù)對象
- function對象
后三者都是類對象,可以看成一種類型
定義基礎(chǔ)模板類
template <typename T> struct function_traits;針對函數(shù)指針進(jìn)行偏特化
對于函數(shù)指針,存在兩種情況
- 直接通過decltype獲取類型
- 利用模板推導(dǎo)類型
不難發(fā)現(xiàn),函數(shù)指針的類型為
- R(*)(Args…)
- R(&)(Args…)
- R(Args…)
其中R是函數(shù)返回值類型,Args是函數(shù)的參數(shù)列表,針對這三種進(jìn)行特化
template <typename R, typename... Args> struct function_traits_helper {static constexpr auto param_count = sizeof...(Args);using return_type = R;template <std::size_t N>using param_type = std::tuple_element_t<N, std::tuple<Args...>>; };// int(*)(int, int) template <typename R, typename... Args> struct function_traits<R(*)(Args...)> : public function_traits_helper<R, Args...> { };// int(&)(int, int) template <typename R, typename... Args> struct function_traits<R(&)(Args...)> : public function_traits_helper<R, Args...> { };// int(int, int) template <typename R, typename... Args> struct function_traits<R(Args...)> : public function_traits_helper<R, Args...> { };針對lambda進(jìn)行偏特化
假設(shè)在main函數(shù)中定義一個匿名函數(shù)lambda,通過模板參數(shù)類型推導(dǎo)判斷它的類型
template <typename Func> void traits_test(Func&&) {}int main() {auto f = [](int a, int b) { return a + b; };// Func = main()::<lambda(int, int)> const// Func::operator() = int(main()::<lambda(int, int)>*)(int, int) consttraits_test(f);return 0; }lambda實際上是一個匿名函數(shù)對象,可以理解為內(nèi)部也重載了operator()函數(shù),所以如果將lambda整體進(jìn)行推導(dǎo),那么會推導(dǎo)出一個main()::
template <typename R, typename... Args> struct function_traits_helper {static constexpr auto param_count = sizeof...(Args);using return_type = R;template <std::size_t N>using param_type = std::tuple_element_t<N, std::tuple<Args...>>; };template <typename ClassType, typename R, typename... Args> struct function_traits<R(ClassType::*)(Args...) const> : public function_traits_helper<R, Args...> {using class_type = ClassType; };template <typename T> struct function_traits : public function_traits<decltype(&T::operator())> {};通過std::function和std::bind綁定的函數(shù)對象和lambda類型相同,不需要額外的特化
增加const版本
針對某些可能推導(dǎo)出const的增加const版本,比如上述的lambda
完整代碼請參考這里
總結(jié)
以上是生活随笔為你收集整理的C++代码片段(一)萃取函数返回值类型,参数类型,参数个数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 每天一道LeetCode-----判断给
- 下一篇: C++代码片段(二)判断可变模板参数中是