cast.h 2.56 KB
Newer Older
1
2
3
4
/**
 * @date Wed Feb 9 12:26:11 2011 +0100
 * @author Laurent El Shafey <Laurent.El-Shafey@idiap.ch>
 *
5
6
 * @brief This file defines easy-to-use Blitz++ cast functions for Bob
 * applications.
7
8
9
10
11
12
13
14
15
 *
 * Copyright (C) Idiap Research Institute, Martigny, Switzerland
 */

#ifndef BOB_CORE_CAST_H
#define BOB_CORE_CAST_H

#include <bob.core/assert.h>
#include <blitz/array.h>
16
#include <complex>
17
18
19

namespace bob { namespace core {

20
21
  namespace array {

22
23
24
25
26
27
    template<typename T, typename U>
      struct scalar_cast_impl {
        static T f(const U& u) {
          return static_cast<T>(u);
        }
      };
28

29
30
31
32
33
34
35
36
37
    template<typename T, typename U>
      struct scalar_cast_impl<T, std::complex<U> > {
        static T f(const std::complex<U>& u) {
          return static_cast<T>(u.real());
        }
      };

    template<typename T, typename U> T scalar_cast(const U& u) {
      return scalar_cast_impl<T,U>::f(u);
38
39
40
    }

    // when using matching complex or non-complex T and U
41
42
43
44
45
    template<typename T, typename U>
      blitz::Array<T,1> cast(const blitz::Array<U,1>& in) {
        bob::core::array::assertZeroBase(in);
        blitz::Array<T,1> out(in.extent(0));
        for( int i=0; i<in.extent(0); ++i)
46
          out(i) = scalar_cast<T,U>(in(i));
47
48
49
50
51
52
53
54
55
        return out;
      }

    template<typename T, typename U>
      blitz::Array<T,2> cast(const blitz::Array<U,2>& in) {
        bob::core::array::assertZeroBase(in);
        blitz::Array<T,2> out(in.extent(0),in.extent(1));
        for( int i=0; i<in.extent(0); ++i)
          for( int j=0; j<in.extent(1); ++j)
56
            out(i,j) = scalar_cast<T,U>(in(i,j));
57
58
59
60
61
62
63
64
65
66
        return out;
      }

    template<typename T, typename U>
      blitz::Array<T,3> cast(const blitz::Array<U,3>& in) {
        bob::core::array::assertZeroBase(in);
        blitz::Array<T,3> out(in.extent(0),in.extent(1),in.extent(2));
        for( int i=0; i<in.extent(0); ++i)
          for( int j=0; j<in.extent(1); ++j)
            for( int k=0; k<in.extent(2); ++k)
67
              out(i,j,k) = scalar_cast<T>(in(i,j,k));
68
69
70
71
72
73
74
75
76
77
78
        return out;
      }

    template<typename T, typename U>
      blitz::Array<T,4> cast(const blitz::Array<U,4>& in) {
        bob::core::array::assertZeroBase(in);
        blitz::Array<T,4> out(in.extent(0),in.extent(1),in.extent(2),in.extent(3));
        for( int i=0; i<in.extent(0); ++i)
          for( int j=0; j<in.extent(1); ++j)
            for( int k=0; k<in.extent(2); ++k)
              for( int l=0; l<in.extent(3); ++l)
79
                out(i,j,k,l) = scalar_cast<T,U>(in(i,j,k,l));
80
81
82
83
84
85
        return out;
      }

  }

}}
86
87

#endif /* BOB_CORE_CAST_H */