NTRT Simulator
 All Classes Files Functions Variables Typedefs Friends Pages
tgCast.h
Go to the documentation of this file.
1 /*
2  * Copyright © 2012, United States Government, as represented by the
3  * Administrator of the National Aeronautics and Space Administration.
4  * All rights reserved.
5  *
6  * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed
7  * under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * http://www.apache.org/licenses/LICENSE-2.0.
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
15  * either express or implied. See the License for the specific language
16  * governing permissions and limitations under the License.
17 */
18 
19 #ifndef TG_CAST_H
20 #define TG_CAST_H
21 
29 // This application
30 #include "tgTagSearch.h"
31 #include "tgTaggable.h"
32 // The C++ Standard Library
33 #include <vector>
34 
38 class tgCast
39 {
40 public:
41 
49  template <typename T_FROM, typename T_TO>
50  static std::vector<T_TO*> filter(const std::vector<T_FROM*>& v)
51  {
52  std::vector<T_TO*> result;
53  for(int i = 0; i < v.size(); i++) {
54  T_TO* t = cast<T_FROM, T_TO>(v[i]);
55  if(t != 0) {
56  result.push_back(t);
57  }
58  }
59  return result;
60  }
61 
65  template <typename T_FROM, typename T_TO>
66  static T_TO* cast(T_FROM* obj)
67  {
68  // @todo: dynamic_cast may just return 0 on fail...
69  try {
70  return dynamic_cast<T_TO*>(obj);
71  } catch (std::exception& e) {
72  return 0;
73  }
74  }
75 
79  template <typename T_FROM, typename T_TO>
80  static T_TO* cast(T_FROM& obj)
81  {
82  return cast<T_FROM, T_TO>(&obj);
83  }
84 
85 
86  template <typename T_FROM, typename T_TO>
87  static std::vector<T_TO*> find(const tgTagSearch& tagSearch, const std::vector<T_FROM*> haystack)
88  {
89  // Filter to the correct type
90  std::vector<T_TO*> filtered = filter<T_FROM, T_TO>(haystack);
91  std::vector<T_TO*> result;
92 
93  // Check each element in filtered to see if it is castable to tgTaggable and matches the search
94  for(int i = 0; i < filtered.size(); i++) {
95  tgTaggable* t = cast<T_TO, tgTaggable>(filtered[i]);
96  if(t != 0 && tagSearch.matches(*t)) {
97  // Note: add filtered[i] instead of t to maintain correct type
98  result.push_back(filtered[i]);
99  }
100  }
101  return result;
102  }
103 
104 };
105 
106 
107 #endif
static T_TO * cast(T_FROM &obj)
Definition: tgCast.h:80
static T_TO * cast(T_FROM *obj)
Definition: tgCast.h:66
Contains the definition of class tgTagSearch $Id$.
Definition: tgCast.h:38
const bool matches(const tgTags &tags) const
Definition: tgTagSearch.h:61
Contains the definition of class tgTaggable $Id$.
static std::vector< T_TO * > filter(const std::vector< T_FROM * > &v)
Definition: tgCast.h:50