Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <tuple>
#include <functional>
#include <iostream>
#include <cassert>
#include <cstdlib>
template<int ...>
struct seq { };
template<int N, int ...S>
struct gens : gens<N-1, N-1, S...> { };
template<int ...S>
struct gens<0, S...> {
typedef seq<S...> type;
};
// 第2引数以降の引数が部分適用された関数オブジェクトを作り出すクラス
template<class RetType, class T, class...Args>
class PartialApplyer {
public:
using Funct = std::function<RetType(T, Args...)>;
private:
Funct f_;
std::tuple<Args...> args_;
public:
template<class FT>
PartialApplyer(FT f, Args...args) : f_(f), args_(args...) {
}
RetType operator()(T t) {
return dispatch(t, typename gens<sizeof...(Args)>::type());
}
private:
template<int...SS>
RetType dispatch(T t, seq<SS...>) {
return f_(t, std::get<SS>(args_)...);
}
};
int multiply(int x, int y, int z) {
return x * y * z;
}
int main() {
// 第2, 第3引数としてあらかじめ "5", "20" を部分適用
PartialApplyer<int, int, int, int> par(multiply, 5, 20);
// さらに40を渡して関数実行.
std::cout << par(40) << std::endl; // => 4000 (= 5 * 20 * 40)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.