Skip to content

Instantly share code, notes, and snippets.

@fcortes
Last active December 7, 2016 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcortes/3933d0ef635cfc7f6912607ff836e6ed to your computer and use it in GitHub Desktop.
Save fcortes/3933d0ef635cfc7f6912607ff836e6ed to your computer and use it in GitHub Desktop.
Templates example
#include "linear_operator.h"
template<class F, class G>
Vector<G> LinearOperator<F, G>::Apply(const Vector<F>& vec) const {
G* dt = new G[vec.GetLength()];
for(int i = 0; i < vec.GetLength(); i++) {
dt[i] = vec.Get(i) * 2;
}
return Vector<G>(vec.GetLength(), dt);
}
template<class F, class G>
Vector<F> LinearOperator<F, G>::Adjoint(const Vector<G>& vec) const {
F* dt = new F[vec.GetLength()];
for(int i = 0; i < vec.GetLength(); i++) {
dt[i] = vec.Get(i) * 0.5;
}
return Vector<F>(vec.GetLength(), dt);
}
//template class LinearOperator<double, double>;
#pragma once
#include "vector.h"
template<class F, class G>
class LinearOperator {
public:
Vector<G> Apply(const Vector<F>&) const;
Vector<F> Adjoint(const Vector<G>&) const;
};
#include <iostream>
#include "linear_operator.h"
#include "vector.h"
int main() {
double d[] = {0.1, 0.2, 0.3};
Vector<double> u = Vector<double>(3, d);
LinearOperator<double, double> linop = LinearOperator<double, double>();
Vector<double> v = linop.Apply(u);
for(int i = 0; i < 3; i++) {
std::cout << v.Get(i) << std::endl;
}
}
#pragma once
template<class F>
class Vector {
private:
int length;
F* data;
public:
Vector(int length, F* data) : length(length), data(data) {};
int GetLength() const { return length; }
F* GetData() { return data; }
F Get(int i) const { return data[i]; }
void Set(int i, F v) { data[i] = v; }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment