Skip to content

Instantly share code, notes, and snippets.

@xtofl
Last active October 20, 2017 07:36
Show Gist options
  • Select an option

  • Save xtofl/9f4a0083ddb7009350de66cc55c18b93 to your computer and use it in GitHub Desktop.

Select an option

Save xtofl/9f4a0083ddb7009350de66cc55c18b93 to your computer and use it in GitHub Desktop.
intuitive string-to-type conversion in C++ using user defined conversion; use `int i = val("22");`
#include "headers.h"
struct Val_t {
const std::string_view s;
template<typename T>
operator T() const { return S<T>::cast(s); }
// can't have partial function specialization,
// hence we use an intermediate structure
template<typename T>
struct S {
static T cast(const std::string_view &s);
};
};
using namespace std;
template<> int Val_t::S<int>::cast(const string_view &s) { return 22; }
template<typename T>
//#define IF_ONLY_I_COULD_WRITE
#ifdef IF_ONLY_I_COULD_WRITE
// error C2244: 'Val_t::S<std::vector<T,std::allocator<_Ty>>>::cast': unable to match function definition to an existing declaration
auto Val_t::S<vector<T>>::cast(const string_view &s) {
return vector<T>{ 1, 2, 4 };
}
#else
struct Val_t::S<vector<T>> {
static auto Val_t::S<vector<T>>::cast(const string_view &s) {
return vector<T>{ 1, 2, 4 };
}
};
#endif
int main()
{
int i = Val_t{"22"};
assert(i == 22);
vector<int> ints = Val_t{"1, 2, 4"};
assert((ints == vector<int>{ 1, 2, 4 }));
}
#include <iostream>
#include <string>
#include <stdexcept>
#include <vector>
#include <iterator>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <string_view>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment