robust_cast.hpp

00001 /*
00002 This file is part of GraphLab.
00003 
00004 GraphLab is free software: you can redistribute it and/or modify
00005 it under the terms of the GNU Lesser General Public License as 
00006 published by the Free Software Foundation, either version 3 of 
00007 the License, or (at your option) any later version.
00008 
00009 GraphLab is distributed in the hope that it will be useful,
00010 but WITHOUT ANY WARRANTY; without even the implied warranty of
00011 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012 GNU Lesser General Public License for more details.
00013 
00014 You should have received a copy of the GNU Lesser General Public 
00015 License along with GraphLab.  If not, see <http://www.gnu.org/licenses/>.
00016 */
00017 
00018 #ifndef GRAPHLAB_ROBUST_CAST_HPP
00019 #define GRAPHLAB_ROBUST_CAST_HPP
00020 
00021 #include <boost/utility.hpp>
00022 #include <boost/type_traits/is_convertible.hpp>
00023 namespace graphlab {
00024   /** robust_cast performs a static cast from type A to type B
00025       if a cast can be done. Return B() otherwise */
00026   
00027   template <typename Target, typename Source>
00028   typename boost::disable_if_c<boost::is_convertible<Source, Target>::value, 
00029                                Target>::type
00030                                robust_cast(const Source &h) {
00031     return Target();
00032   }
00033   
00034   template <typename Target, typename Source>
00035   typename boost::enable_if_c<boost::is_convertible<Source, Target>::value, 
00036                               Target>::type
00037                               robust_cast(const Source &h) {
00038     return (Target)h;
00039   }
00040 }
00041 
00042 #endif
00043 
00044