1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include <map>
#include <cstdarg>
#include <vector>
#include <functional>
#include <initializer_list>
#include <iostream> // <--
template<typename T, typename ... Args>
class Function {
private:
std::map<char,T> va;
std::vector<std::function<T(T, Args...)>> terms;
public:
template<typename... Params>
Function(Params... params) {
for(auto c : {params...})
va.insert({c, T()});
}
T operator()(T t, Args ... args) {
T result = 0;
for(long unsigned int i=0; i<terms.size(); i++) result += terms[i](t, args...);
return result;
}
Function& operator=(std::initializer_list<std::function<T(T, Args...)>> array) { // <--
for(long unsigned int i=0; i<array.size(); i++) terms.push_back(std::data(array)[i]);
return *this;
}
};
int p5(int x, int y) {
return x*y;
}
int p6(int x, int y) {
return x+y;
}
float p7(float x, float y) {
return x*y;
}
float p8(float x, float y) {
return x+y;
}
int main(int, char **) {
Function<int, int> f1('x', 'y'); // <--
f1 = {p5, p6};
std::cout << f1(3, 2) << std::endl;
Function<float, float> f2('x', 'y'); // <--
f2 = {p7, p8};
std::cout << f2(2.5f, 1.5f) << std::endl;
return 0;
}
|