Skip to content

Instantly share code, notes, and snippets.

@r-lyeh-archived
Created April 19, 2016 11:47
Show Gist options
  • Save r-lyeh-archived/a7d7f13294a36983d85e21d826783b4a to your computer and use it in GitHub Desktop.
Save r-lyeh-archived/a7d7f13294a36983d85e21d826783b4a to your computer and use it in GitHub Desktop.
another small variant class
// another small variant class
// - rlyeh, public domain
#pragma once
#include <string>
#include <sstream>
template< typename T >
inline T as( const std::string &self ) {
T t;
if( std::istringstream(self) >> t )
return t;
bool is_true = self.size() && (self != "0") && (self != "false");
return (T)(is_true);
}
template<>
inline char as( const std::string &self ) {
return self.size() == 1 ? (char)(self[0]) : (char)(as<int>(self));
}
template<>
inline signed char as( const std::string &self ) {
return self.size() == 1 ? (signed char)(self[0]) : (signed char)(as<int>(self));
}
template<>
inline unsigned char as( const std::string &self ) {
return self.size() == 1 ? (unsigned char)(self[0]) : (unsigned char)(as<int>(self));
}
template<>
inline const char *as( const std::string &self ) {
return self.c_str();
}
template<>
inline std::string as( const std::string &self ) {
return self;
}
struct variant : public std::string {
template<typename T>
variant( const T &t ) : std::string( std::to_string(t) )
{}
template<size_t N>
variant( const char (&s)[N] ) : std::string( s, N )
{}
variant( const char *cstr ) : std::string( cstr )
{}
variant( const std::string &other = std::string() ) : std::string(other)
{}
template<typename T>
operator T() const { /*
T t;
std::stringstream ss;
return ss << *this && ss >> t ? t : T();
*/
return as<T>( *this );
}
template<typename T> bool operator ==( const T &t ) const {
return 0 == this->compare( variant( t ) );
}
bool operator ==( const char *t ) const {
return this->compare( t ) == 0;
}
template<typename T> bool operator !=( const T &t ) const {
return !operator ==( t );
}
bool operator !=( const char *t ) const {
return !operator ==( t );
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment