Last active
September 17, 2015 04:45
-
-
Save keisukefukuda/cef80d18f4b6819bb556 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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