Related
I would like to ask you for help with the programming headache I face last few days. Let me try to explain what I am about to implement...
My goal is to define a set of equations with its validity. Let me explain more in detail...
I think about being each equation object a functor - a class defining the operator(). The definition of this operator should be specialized for each equation type. The specialization contains the calculation itself:
.h:
enum class IDs : int { A = 0, B = 1, C = 2 };
template<IDs WHICH>
struct Equation
{
int operator() ( void );
}
.cpp:
template<>
Equation<IDs::A>::operator()( void )
{
/* Just some sample equation */
return( 42 + 28 );
}
As you may have noticed, the specialization is defined by enum class member IDs::?.
This seems to be working. But I would like to add so called availability feature - The equation may be valid only for certain user object types.
There is 'validity group' declared:
/* Object types declaration */
namespace Objects {
using Object0 = boost::mpl::int_<0>;
using Object1 = boost::mpl::int_<1>;
using Object2 = boost::mpl::int_<2>;
}
/* Validity groups declaration */
using ValidityGroup1 = boost::mpl::vector<Object0, Object2>;
using ValidityGroup2 = boost::mpl::vector<Object1>;
I am using the following construct to make the class enabled or disabled (using boost::enable_if). Just to show how I use it:
template<typename TYPE_LIST, typename QUERY_TYPE>
struct IsTypeInList
{
using TypePos = typename boost::mpl::find<TYPE_LIST, QUERY_TYPE>::type;
using Finish = typename boost::mpl::end<TYPE_LIST>::type;
using type = typename boost::mpl::not_<boost::is_same<TypePos, Finish> >::type;
using value_type = typename type::value_type;
static const bool value = type::value;
};
template<typename OBJECT_TYPE, typename ENABLER=void>
class SampleClass;
template<typename OBJECT_TYPE>
class SampleClass<OBJECT_TYPE, typename boost::enable_if<typename IsTypeInList<ValidityGroup1, Object0>::type>::type>
{}
The partial specialization of SampleClass is available only if Object0 belongs to ValidityGroup1. So far so good. This principle is verified.
Now the funny stuff comes. I would like to merge the two things together:
THE GOAL:
Define Equation's operator() who's specialization containing valid body is defined by IDs::?? enum class value" and is available only for Object belonging to ValidityGroup... There can be another calculation of the same IDs::?? but valid for Object in other ValidityGroup (aka Object0's property is calculated some other way than for Object1)
I know the whole concept is quite complicated and may be confusing. Let me show my attempt to implement this stuff:
template<typename OBJECT_TYPE, typename VALIDITY_GROUP, IDs ID, typename ENABLER = void>
class Equation;
template<typename OBJECT_TYPE, typename VALIDITY_GROUP, IDs ID>
class Equation<OBJECT_TYPE, VALIDITY_GROUP, ID, typename boost::enable_if<typename IsTypeInList<VALIDITY_GROUP, OBJECT_TYPE>::type>::type >
: public EquationBase<IDs>
{
public:
int operator() ( void );
};
template<typename OBJECT_TYPE, typename VALIDITY_GROUP, IDs ID>
int Equation<OBJECT_TYPE, ValidityGroup1, Ids::A>::operator() ( void )
{
return( 42 + 56 );
}
But the operator() definition is not working... Could you please advise me how to make this working? Or does anyone have any other idea how to fulfill the goal written above?
Many thanks in advance to anybody willing to help me...
Cheers Martin
EDIT:
The equation is used in template class object. Let the code explain:
template<typename OBJECT_TYPE>
class Object
{
public:
Object( void );
};
.cpp:
template<typename OBJECT_TYPE>
Object<OBJECT_TYPE>::Object( void )
{
std::cout << Equation<IDs::A>()() << std::endl;
}
The problem is OBJECT_TYPE is not defined when the operators () are specialized...
If I understand correctly what you want to obtain, I suppose there are many ways.
The following is a iper-semplified example (but complete ad working) that show how to select different implementations using std::enable_if (but boost::enable_if should be OK) with the return type of the operator
#include <iostream>
#include <type_traits>
template <typename ObjT, typename ValT>
class Equation
{
public:
template <typename X = ObjT>
typename std::enable_if<true == std::is_same<X, ValT>::value, int>::type
operator() ( void )
{ return( 0 ); }
template <typename X = ObjT>
typename std::enable_if<false == std::is_same<X, ValT>::value, int>::type
operator() ( void )
{ return( 1 ); }
};
int main()
{
Equation<int, int> eq0;
Equation<int, long> eq1;
std::cout << "eq0 val: " << eq0() << std::endl; // print "eq0 val: 0"
std::cout << "eq1 val: " << eq1() << std::endl; // print "eq1 val: 1"
}
Not really elegant, I suppose.
Another solution (that, I suppose, best fits your desiderata) could be the following based on class partial specialization
#include <iostream>
#include <type_traits>
template <typename ObjT, typename ValT, bool = std::is_same<ObjT, ValT>::value>
class Equation;
template <typename ObjT, typename ValT>
class Equation<ObjT, ValT, true>
{
public:
int operator() ();
};
template <typename ObjT, typename ValT>
class Equation<ObjT, ValT, false>
{
public:
int operator() ();
};
template <typename ObjT, typename ValT>
int Equation<ObjT, ValT, true>::operator() ()
{ return( 0 ); }
template <typename ObjT, typename ValT>
int Equation<ObjT, ValT, false>::operator() ()
{ return( 1 ); }
int main()
{
Equation<int, int> eq0;
Equation<int, long> eq1;
std::cout << "eq0 val: " << eq0() << std::endl; // print "eq0 val: 0"
std::cout << "eq1 val: " << eq1() << std::endl; // print "eq1 val: 1"
}
Consider the following:
template<typename T>
struct S
{
typedef M< &T::foo > MT;
}
This would work for:
S<Widget> SW;
where Widget::foo() is some function
How would I modify the definition of struct S to allow the following instead:
S<Widget*> SWP;
What you need is the following type transformation.
given T, return T
given T *, return T
It so happens that the standard library already has implemented this for us in std::remove_pointer (though it's not hard to do yourself).
With this, you can then write
using object_type = std::remove_pointer_t<T>;
using return_type = /* whatever foo returns */;
using MT = M<object_type, return_type, &object_type::foo>;
Regarding your comment that you also want to work with smart pointers, we have to re-define the type transformation.
given a smart pointer type smart_ptr<T>, return smart_ptr<T>::element_type, which should be T
given a pointer type T *, return T
otherwise, given T, return T itself
For this, we'll have to code our own meta-function. At least, I'm not aware of anything in the standard library that would help here.
We start by defining the primary template (the “otherwise” case).
template <typename T, typename = void>
struct unwrap_obect_type { using type = T; };
The second (anonymous) type parameter that is defaulted to void will be of use later.
For (raw) pointers, we provide the following partial specialization.
template <typename T>
struct unwrap_obect_type<T *, void> { using type = T; };
If we'd stop here, we'd basically get std::remove_pointer. But we'll add an additional partial specialization for smart pointers. Of course, we'll first have to define what a “smart pointer” is. For the purpose of this example, we'll treat every type with a nested typedef named element_type as a smart pointer. Adjust this definition as you see fit.
template <typename T>
struct unwrap_obect_type
<
T,
std::conditional_t<false, typename T::element_type, void>
>
{
using type = typename T::element_type;
};
The second type parameter std::conditional_t<false, typename T::element_type, void> is a convoluted way to simulate std::void_t in C++14. The idea is that we have the following partial type function.
given a type T with a nested typedef named element_type, return void
otherwise, trigger a substitution failure
Therefore, if we are dealing with a smart pointer, we'll get a better match than the primary template and otherwise, SFINAE will remove this partial specialization from further consideration.
Here is a working example. T.C. has suggested using std::mem_fn to invoke the member function. This makes the code a lot cleaner than my initial example.
#include <cstddef>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
template <typename ObjT, typename RetT, RetT (ObjT::*Pmf)() const noexcept>
struct M
{
template <typename ThingT>
static RetT
call(ThingT&& thing) noexcept
{
auto wrapper = std::mem_fn(Pmf);
return wrapper(std::forward<ThingT>(thing));
}
};
template <typename T, typename = void>
struct unwrap_obect_type { using type = T; };
template <typename T>
struct unwrap_obect_type<T *, void> { using type = T; };
template <typename T>
struct unwrap_obect_type<T, std::conditional_t<false, typename T::element_type, void>> { using type = typename T::element_type; };
template <typename T>
struct S
{
template <typename ThingT>
void
operator()(ThingT&& thing) const noexcept
{
using object_type = typename unwrap_obect_type<T>::type;
using id_caller_type = M<object_type, int, &object_type::id>;
using name_caller_type = M<object_type, const std::string&, &object_type::name>;
using name_length_caller_type = M<object_type, std::size_t, &object_type::name_length>;
std::cout << "id: " << id_caller_type::call(thing) << "\n";
std::cout << "name: " << name_caller_type::call(thing) << "\n";
std::cout << "name_length: " << name_length_caller_type::call(thing) << "\n";
}
};
class employee final
{
private:
int id_ {};
std::string name_ {};
public:
employee(int id, std::string name) : id_ {id}, name_ {std::move(name)}
{
}
int id() const noexcept { return this->id_; }
const std::string& name() const noexcept { return this->name_; }
std::size_t name_length() const noexcept { return this->name_.length(); }
};
int
main()
{
const auto bob = std::make_shared<employee>(100, "Smart Bob");
const auto s_object = S<employee> {};
const auto s_pointer = S<employee *> {};
const auto s_smart_pointer = S<std::shared_ptr<employee>> {};
s_object(*bob);
std::cout << "\n";
s_pointer(bob.get());
std::cout << "\n";
s_smart_pointer(bob);
}
I have a template class where each template argument stands for one type of value the internal computation can handle. Templates (instead of function overloading) are needed because the values are passed as boost::any and their types are not clear before runtime.
To properly cast to the correct types, I would like to have a member list for each variadic argument type, something like this:
template<typename ...AcceptedTypes> // e.g. MyClass<T1, T2>
class MyClass {
std::vector<T1> m_argumentsOfType1;
std::vector<T2> m_argumentsOfType2; // ...
};
Or alternatively, I'd like to store the template argument types in a list, as to do some RTTI magic with it (?). But how to save them in a std::initializer_list member is also unclear to me.
Thanks for any help!
As you have already been hinted, the best way is to use a tuple:
template<typename ...AcceptedTypes> // e.g. MyClass<T1, T2>
class MyClass {
std::tuple<std::vector<AcceptedTypes>...> vectors;
};
This is the only way to multiply the "fields" because you cannot magically make it spell up the field names. Another important thing may be to get some named access to them. I guess that what you're trying to achieve is to have multiple vectors with unique types, so you can have the following facility to "search" for the correct vector by its value type:
template <class T1, class T2>
struct SameType
{
static const bool value = false;
};
template<class T>
struct SameType<T, T>
{
static const bool value = true;
};
template <typename... Types>
class MyClass
{
public:
typedef std::tuple<vector<Types>...> vtype;
vtype vectors;
template<int N, typename T>
struct VectorOfType: SameType<T,
typename std::tuple_element<N, vtype>::type::value_type>
{ };
template <int N, class T, class Tuple,
bool Match = false> // this =false is only for clarity
struct MatchingField
{
static vector<T>& get(Tuple& tp)
{
// The "non-matching" version
return MatchingField<N+1, T, Tuple,
VectorOfType<N+1, T>::value>::get(tp);
}
};
template <int N, class T, class Tuple>
struct MatchingField<N, T, Tuple, true>
{
static vector<T>& get(Tuple& tp)
{
return std::get<N>(tp);
}
};
template <typename T>
vector<T>& access()
{
return MatchingField<0, T, vtype,
VectorOfType<0, T>::value>::get(vectors);
}
};
Here is the testcase so you can try it out:
int main( int argc, char** argv )
{
int twelf = 12.5;
typedef reference_wrapper<int> rint;
MyClass<float, rint> mc;
vector<rint>& i = mc.access<rint>();
i.push_back(twelf);
mc.access<float>().push_back(10.5);
cout << "Test:\n";
cout << "floats: " << mc.access<float>()[0] << endl;
cout << "ints: " << mc.access<rint>()[0] << endl;
//mc.access<double>();
return 0;
}
If you use any type that is not in the list of types you passed to specialize MyClass (see this commented-out access for double), you'll get a compile error, not too readable, but gcc at least points the correct place that has caused the problem and at least such an error message suggests the correct cause of the problem - here, for example, if you tried to do mc.access<double>():
error: ‘value’ is not a member of ‘MyClass<float, int>::VectorOfType<2, double>’
An alternate solution that doesn't use tuples is to use CRTP to create a class hierarchy where each base class is a specialization for one of the types:
#include <iostream>
#include <string>
template<class L, class... R> class My_class;
template<class L>
class My_class<L>
{
public:
protected:
L get()
{
return val;
}
void set(const L new_val)
{
val = new_val;
}
private:
L val;
};
template<class L, class... R>
class My_class : public My_class<L>, public My_class<R...>
{
public:
template<class T>
T Get()
{
return this->My_class<T>::get();
}
template<class T>
void Set(const T new_val)
{
this->My_class<T>::set(new_val);
}
};
int main(int, char**)
{
My_class<int, double, std::string> c;
c.Set<int>(4);
c.Set<double>(12.5);
c.Set<std::string>("Hello World");
std::cout << "int: " << c.Get<int>() << "\n";
std::cout << "double: " << c.Get<double>() << "\n";
std::cout << "string: " << c.Get<std::string>() << std::endl;
return 0;
}
One way to do such a thing, as mentioned in πάντα-ῥεῖ's comment is to use a tuple. What he didn't explain (probably to save you from yourself) is how that might look.
Here is an example:
using namespace std;
// define the abomination
template<typename...Types>
struct thing
{
thing(std::vector<Types>... args)
: _x { std::move(args)... }
{}
void print()
{
do_print_vectors(std::index_sequence_for<Types...>());
}
private:
template<std::size_t... Is>
void do_print_vectors(std::index_sequence<Is...>)
{
using swallow = int[];
(void)swallow{0, (print_one(std::get<Is>(_x)), 0)...};
}
template<class Vector>
void print_one(const Vector& v)
{
copy(begin(v), end(v), ostream_iterator<typename Vector::value_type>(cout, ","));
cout << endl;
}
private:
tuple<std::vector<Types>...> _x;
};
// test it
BOOST_AUTO_TEST_CASE(play_tuples)
{
thing<int, double, string> t {
{ 1, 2, 3, },
{ 1.1, 2.2, 3.3 },
{ "one"s, "two"s, "three"s }
};
t.print();
}
expected output:
1,2,3,
1.1,2.2,3.3,
one,two,three,
There is a proposal to allow this kind of expansion, with the intuitive syntax: P1858R1 Generalized pack declaration and usage. You can also initialize the members and access them by index. You can even support structured bindings by writing using... tuple_element = /*...*/:
template <typename... Ts>
class MyClass {
std::vector<Ts>... elems;
public:
using... tuple_element = std::vector<Ts>;
MyClass() = default;
explicit MyClass(std::vector<Ts>... args) noexcept
: elems(std::move(args))...
{
}
template <std::size_t I>
requires I < sizeof...(Ts)
auto& get() noexcept
{
return elems...[I];
}
template <std::size_t I>
requires I < sizeof...(Ts)
const auto& get() const
{
return elems...[I];
}
// ...
};
Then the class can be used like this:
using Vecs = MyClass<int, double>;
Vecs vecs{};
vecs.[0].resize(3, 42);
std::array<double, 4> arr{1.0, 2.0, 4.0, 8.0};
vecs.[1] = {arr.[:]};
// print the elements
// note the use of vecs.[:] and Vecs::[:]
(std::copy(vecs.[:].begin(), vecs.[:].end(),
std::ostream_iterator<Vecs::[:]>{std::cout, ' '},
std::cout << '\n'), ...);
Here is a less than perfectly efficient implementation using boost::variant:
template<typename ... Ts>
using variant_vector = boost::variant< std::vector<Ts>... >;
template<typename ...Ts>
struct MyClass {
using var_vec = variant_vector<Ts...>;
std::array<var_vec, sizeof...(Ts)> vecs;
};
we create a variant-vector that can hold one of a list of types in it. You have to use boost::variant to get at the contents (which means knowing the type of the contents, or writing a visitor).
We then store an array of these variant vectors, one per type.
Now, if your class only ever holds one type of data, you can do away with the array, and just have one member of type var_vec.
I cannot see why you'd want one vector of each type. I could see wanting a vector where each element is one of any type. That would be a vector<variant<Ts...>>, as opposed to the above variant<vector<Ts>...>.
variant<Ts...> is the boost union-with-type. any is the boost smart-void*. optional is the boost there-or-not.
template<class...Ts>
boost::optional<boost::variant<Ts...>> to_variant( boost::any );
may be a useful function, that takes an any and tries to convert it to any of the Ts... types in the variant, and returns it if it succeeds (and returns an empty optional if not).
Is there a way, presumably using templates, macros or a combination of the two, that I can generically apply a function to different classes of objects but have them respond in different ways if they do not have a specific function?
I specifically want to apply a function which will output the size of the object (i.e. the number of objects in a collection) if the object has that function but will output a simple replacement (such as "N/A") if the object doesn't. I.e.
NO_OF_ELEMENTS( mySTLMap ) -----> [ calls mySTLMap.size() to give ] ------> 10
NO_OF_ELEMENTS( myNoSizeObj ) --> [ applies compile time logic to give ] -> "N/A"
I expect that this might be something similar to a static assertion although I'd clearly want to compile a different code path rather than fail at build stage.
From what I understand, you want to have a generic test to see if a class has a certain member function. This can be accomplished in C++ using SFINAE. In C++11 it's pretty simple, since you can use decltype:
template <typename T>
struct has_size {
private:
template <typename U>
static decltype(std::declval<U>().size(), void(), std::true_type()) test(int);
template <typename>
static std::false_type test(...);
public:
typedef decltype(test<T>(0)) type;
enum { value = type::value };
};
If you use C++03 it is a bit harder due to the lack of decltype, so you have to abuse sizeof instead:
template <typename T>
struct has_size {
private:
struct yes { int x; };
struct no {yes x[4]; };
template <typename U>
static typename boost::enable_if_c<sizeof(static_cast<U*>(0)->size(), void(), int()) == sizeof(int), yes>::type test(int);
template <typename>
static no test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(yes) };
};
Of course this uses Boost.Enable_If, which might be an unwanted (and unnecessary) dependency. However writing enable_if yourself is dead simple:
template<bool Cond, typename T> enable_if;
template<typename T> enable_if<true, T> { typedef T type; };
In both cases the method signature test<U>(int) is only visible, if U has a size method, since otherwise evaluating either the decltype or the sizeof (depending on which version you use) will fail, which will then remove the method from consideration (due to SFINAE. The lengthy expressions std::declval<U>().size(), void(), std::true_type() is an abuse of C++ comma operator, which will return the last expression from the comma-separated list, so this makes sure the type is known as std::true_type for the C++11 variant (and the sizeof evaluates int for the C++03 variant). The void() in the middle is only there to make sure there are no strange overloads of the comma operator interfering with the evaluation.
Of course this will return true if T has a size method which is callable without arguments, but gives no guarantees about the return value. I assume wou probably want to detect only those methods which don't return void. This can be easily accomplished with a slight modification of the test(int) method:
// C++11
template <typename U>
static typename std::enable_if<!is_void<decltype(std::declval<U>().size())>::value, std::true_type>::type test(int);
//C++03
template <typename U>
static typename std::enable_if<boost::enable_if_c<sizeof(static_cast<U*>(0)->size()) != sizeof(void()), yes>::type test(int);
There was a discussion about the abilities of constexpr some times ago. It's time to use it I think :)
It is easy to design a trait with constexpr and decltype:
template <typename T>
constexpr decltype(std::declval<T>().size(), true) has_size(int) { return true; }
template <typename T>
constexpr bool has_size(...) { return false; }
So easy in fact that the trait loses most of its value:
#include <iostream>
#include <vector>
template <typename T>
auto print_size(T const& t) -> decltype(t.size(), void()) {
std::cout << t.size() << "\n";
}
void print_size(...) { std::cout << "N/A\n"; }
int main() {
print_size(std::vector<int>{1, 2, 3});
print_size(1);
}
In action:
3
N/A
This can be done using a technique called SFINAE. In your specific case you could implement that using Boost.Concept Check. You'd have to write your own concept for checking for a size-method. Alternatively you could use an existing concept such as Container, which, among others, requires a size-method.
You can do something like
template< typename T>
int getSize(const T& t)
{
return -1;
}
template< typename T>
int getSize( const std::vector<T>& t)
{
return t.size();
}
template< typename T , typename U>
int getSize( const std::map<T,U>& t)
{
return t.size();
}
//Implement this interface for
//other objects
class ISupportsGetSize
{
public:
virtual int size() const= 0;
};
int getSize( const ISupportsGetSize & t )
{
return t.size();
}
int main()
{
int s = getSize( 4 );
std::vector<int> v;
s = getSize( v );
return 0;
}
basically the most generic implementation is always return -1 or "NA" but for vector and maps it will return the size. As the most general one always matches there is never a build time failure
Here you go. Replace std::cout with the output of your liking.
template <typename T>
class has_size
{
template <typename C> static char test( typeof(&C::size) ) ;
template <typename C> static long test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};
template<bool T>
struct outputter
{
template< typename C >
static void output( const C& object )
{
std::cout << object.size();
}
};
template<>
struct outputter<false>
{
template< typename C >
static void output( const C& )
{
std::cout << "N/A";
}
};
template<typename T>
void NO_OF_ELEMENTS( const T &object )
{
outputter< has_size<T>::value >::output( object );
}
You could try something like:
#include <iostream>
#include <vector>
template<typename T>
struct has_size
{
typedef char one;
typedef struct { char a[2]; } two;
template<typename Sig>
struct select
{
};
template<typename U>
static one check (U*, select<char (&)[((&U::size)!=0)]>* const = 0);
static two check (...);
static bool const value = sizeof (one) == sizeof (check (static_cast<T*> (0)));
};
struct A{ };
int main ( )
{
std::cout << has_size<int>::value << "\n";
std::cout << has_size<A>::value << "\n";
std::cout << has_size<std::vector<int>>::value << "\n";
}
but you have to be careful, this does neither work when size is overloaded, nor when it is a template. When you can use C++11, you can replace the above sizeof trick by decltype magic
I have a struct:
typedef struct Tick {
double open;
double high;
double low;
double close;
double ema100;
} Tick;
I would like to access a property given a key:
Tick currentTick = {44.5, 45.1, 44.2, 44.6, 44.255};
std::string key = "ema100";
std::cout << currentTick[key];
Is there a way to do this without using std::map? I imagine the answer is no, but I just want to be certain before modifying everything to use std::map and increase my memory requirements.
Is there a way to do this without using std::map?
As long as you are willing to live with a series of cascading if-else statements, you can do that.
I would question the design though.
You can get there partially using tag based member variables. Sample working example:
#include <iostream>
struct OpenTag {};
struct HighTag {};
struct LowTag {};
struct CloseTag {};
struct Ema100Tag {};
struct Tick {
template <typename Tag> struct Member
{
double val;
operator double () const { return val; }
operator double& () { return val; }
};
struct AllMembers : Member<OpenTag>,
Member<HighTag>,
Member<LowTag>,
Member<CloseTag>,
Member<Ema100Tag> {};
AllMembers data;
template <typename Tag>
double operator[](Tag t) const
{
return (Member<Tag> const&)(data);
}
template <typename Tag>
double& operator[](Tag t)
{
return (Member<Tag>&)(data);
}
};
int main()
{
Tick t;
t[OpenTag()] = 12.345;
std::cout << t[OpenTag()] << std::endl;
}
Output:
12.345
The feature you're looking for is called reflection. This is not supported by native C++. You can either check for some 3rd-party libraries to do the reflection for you (but still would require lot of manual effort).
Or the other option is (as you mentioned) using std::map (or rather std::unordered_map as it would perform better) to map the name to id or offset (pointer) of the field within the class and then via switch statement (in former case) or directly using the pointer (in the latter case) modify the field value.
You can do that using metadata available at compile time. However, we must do it manually:
template<typename Class, typename T>
struct Property {
constexpr Property(T Class::*aMember, const char* aName) : member{aMember}, name{aName} {}
using Type = T;
T Class::*member;
const char* name;
};
template<typename Class, typename T>
constexpr auto makeProperty(T Class::*member, const char* name) {
return Property<Class, T>{member, name};
}
Now we have a class that can hold our desired metadata. Here's how to use it:
struct Dog {
constexpr static auto properties = std::make_tuple(
makeProperty(&Dog::barkType, "barkType"),
makeProperty(&Dog::color, "color")
);
private:
std::string barkType;
std::string color;
};
Now we can do iteration on it by recursion:
template<std::size_t iteration, typename T, typename U>
void accessGetByString(T&& object, std::string name, U&& access) {
// get the property
constexpr auto property = std::get<iteration>(std::decay_t<T>::properties);
if (name == property.name) {
std::forward<U>(access)(std::forward<T>(object).*(property.member));
}
}
template<std::size_t iteration, typename T, typename U>
std::enable_if_t<(iteration > 0)>
getByStringIteration(T&& object, std::string name, U&& access) {
accessGetByString<iteration>(std::forward<T>(object), name, std::forward<U>(access));
// next iteration
getByStringIteration<iteration - 1>(std::forward<T>(object), name, std::forward<U>(access));
}
template<std::size_t iteration, typename T, typename U>
std::enable_if_t<(iteration == 0)>
getByStringIteration(T&& object, std::string name, U&& access) {
accessGetByString<iteration>(std::forward<T>(object), name, std::forward<U>(access));
}
template<typename T, typename U>
void getByString(T&& object, std::string name, U&& access) {
getByStringIteration<std::tuple_size<decltype(std::decay_t<T>::properties)>::value - 1>(
std::forward<T>(object),
name,
std::forward<U>(access)
);
}
Then finally, you can use this tool like:
struct MyAccess {
void operator()(int i) { cout << "got int " << i << endl; }
void operator()(double f) { cout << "got double " << f << endl; }
void operator()(std::string s) { cout << "got string " << s << endl; }
}
Dog myDog;
getByString(myDog, "color", MyAccess{});
This for sure could by simplified with overloaded lambda. To know more about overloaded lambda, see this blog post
The original code was taken from that answer: C++ JSON Serialization
There's a proposal to make things like this easier.
This is covered by P0255r0
Honestly i think the use of an overloaded operator[] and if-else statement is all you really need. Given any class, are their really that many members? The other solutions in my opinion provide too much overhead for such a simple task. I would just do something like this:
template <typename T>
T& operator[](const std::string& key)
{
if (key == ...)
// do something
}