首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 實現類似 Common Lisp 的多參數加法與比較

     編輯:關於C++

靈感來源

Common Lisp 支持 (+ 1 2 3) 返回 6,(< 1 2 3) 返回 T。C++11 變參模板可實現類似功能。

實現代碼

#include <functional>

// 多參數比較
template<typename O, typename A, typename B>
bool cmp(O o, A a, B b) { return o(a, b); }

template<typename O, typename A, typename B, typename... C>
bool cmp(O o, A a, B b, C... c) {
    return o(a, b) && cmp(o, b, c...);
}

// 多參數歸約(加法等)
template<typename O, typename A, typename B>
A reduce(O o, A a, B b) { return o(a, b); }

template<typename O, typename A, typename B, typename... C>
A reduce(O o, A a, B b, C... c) {
    return reduce(o, o(a, b), c...);
}

// 使用示例
bool foo(int a, int b, int c, int d) {
    return cmp(std::less<int>(), a, b, c, d);
}

int bar(int a, int b, int c, int d) {
    return reduce(std::plus<int>(), a, b, c, d);
}

原理

  • cmp 遞歸展開:a<b && b<c && c<d。
  • reduce 遞歸累積:((a+b)+c)+d。
  • 配合 std::less、std::plus 等函數對象實現通用操作。

變參模板讓 C++ 具備函數式編程的表達能力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved