Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- void add1(int &v)
- {
- v+=1;
- }
- void add2(int &v)
- {
- v+=2;
- }
- template <void (*T)(int &)>
- void doOperation()
- {
- int temp=0;
- T(temp);
- std::cout << "Result is " << temp << std::endl;
- }
- int main()
- {
- doOperation<add1>();
- doOperation<add2>();
- }
- struct add3 {
- void operator() (int &v) {v+=3;}
- };
- ...
- doOperation<add3>();
- template <typename F>
- void doOperation(F f)
- {
- int temp=0;
- f(temp);
- std::cout << "Result is " << temp << std::endl;
- }
- doOperation(add2);
- doOperation(add3());
- template <void (*T)(int &)>
- void doOperation()
- template <class T>
- void doOperation(T t)
- {
- int temp=0;
- t(temp);
- std::cout << "Result is " << temp << std::endl;
- }
- template<typename OP>
- int do_op(int a, int b, OP op)
- {
- return op(a,b,);
- }
- int add(int a, b) { return a + b; }
- ...
- int c = do_op(4,5,add);
- int (* func_ptr)(int, int) = add;
- int c = do_op(4,5,func_ptr);
- int (* func_ptr)(int,int) = add;
- int c = do_op<func_ptr>(4,5);
- template<typename OP>
- int do_op(int a, int b, OP op) { return op(a,b); }
- float fadd(float a, float b) { return a+b; }
- ...
- int c = do_op(4,5,fadd);
- convert a and b from int to float.
- call the function ptr op with float a and float b.
- convert the result back to int and return it.
- struct Square
- {
- double operator()(double number) { return number * number; }
- };
- template <class Function>
- double integrate(Function& f, double a, double b, unsigned int intervals)
- {
- double delta = (b - a) / intervals, sum = 0.0;
- while(a < b)
- {
- sum += f(a) * delta;
- a += delta;
- }
- return sum;
- }
- std::cout << "interval : " << i << tab << tab << "intgeration = "
- << integrate(Square(), 0.0, 1.0, 10) << std::endl;
Add Comment
Please, Sign In to add comment