Function specialization to access struct members with getter using enum - c++

I have an enum and a struct
enum STORE_ENUM { A_DATA, B_DATA, C_DATA, D_DATA };
struct Store {
int a;
char b;
long c;
bool d;
}
and I want to access its members with a specialized get function that basically looks like this
T get(STORE_ENUM,store s);
and it returns the appropriate type and hopefully statically type checks.
is this possible in C++?

Yes it's possible. The boost PFR library allows something very similar to how you've envisaged it, e.g.:
auto& x = boost::pfr::get<B_DATA>(s);
See the tutorial here.

With C++17, you can do the following
#include <iostream>
enum struct STORE_ENUM { A_DATA, B_DATA, C_DATA, D_DATA };
struct Store {
int a;
char b;
long c;
bool d;
};
template<STORE_ENUM storeEnum>
auto get(Store const & s){
if constexpr (storeEnum == STORE_ENUM::A_DATA) return s.a;
if constexpr (storeEnum == STORE_ENUM::B_DATA) return s.b;
if constexpr (storeEnum == STORE_ENUM::C_DATA) return s.c;
if constexpr (storeEnum == STORE_ENUM::D_DATA) return s.d;
}
int main(){
auto store = Store{ 0, 'a', 4l, true};
std::cout << get<STORE_ENUM::A_DATA>( store) << "\n";
std::cout << get<STORE_ENUM::B_DATA>( store) << "\n";
std::cout << get<STORE_ENUM::C_DATA>( store) << "\n";
std::cout << get<STORE_ENUM::D_DATA>( store) << "\n";
}
See https://godbolt.org/z/1vffh3

In my solution, we don't need enums. It uses templates.
#include <iostream>
#include <type_traits>
struct Store
{
int a;
char b;
long c;
bool d;
Store() //Default constructor
{
a = 0;
b = 0;
c = 0;
d = false;
}
Store(int a, char b, long c, bool d) //Constructor. Custom values.
{
this->a = a;
this->b = b;
this->c = c;
this->d = d;
}
template <typename T = int,
typename = typename std::enable_if<std::is_same<T, int>::value ||
std::is_same<T, char>::value ||
std::is_same<T, long>::value ||
std::is_same<T, bool>::value,
void>::type>
T GetData()
{
if (std::is_same<T, char>::value)
{
return b;
}
if (std::is_same<T, long>::value)
{
return c;
}
if (std::is_same<T, bool>::value)
{
return d;
}
return a;
}
};
int main()
{
Store store { 63, '#', 65, true };
std::cout << store.GetData() << std::endl;
std::cout << store.GetData<>() << std::endl;
std::cout << store.GetData<int>() << std::endl;
std::cout << store.GetData<char>() << std::endl;
std::cout << store.GetData<long>() << std::endl;
std::cout << std::boolalpha << store.GetData<bool>() << std::endl;
}
Output
63
63
63
#
65
true
Compile
clang++ ./main.cpp -std=c++11 or g++ ./main.cpp -std=c++11
Check/run this code in https://repl.it/#JomaCorpFX/FunctionSpecialization#main.cpp

std::tuple basically does this, and your type is basically a tuple. So the easy and fast way is to just reuse std::tuple's machinery.
In c++14 it might look like this:
template<STORE_ENUM e>
auto get( Store s ){
return std::get<(unsigned)e>(std::make_tuple(s.a,s.b,s.c,s.d));
}
template<STORE_ENUM e, class T>
void set( Store& s, T t ){
std::get<(unsigned)e>(std::tie(s.a,s.b,s.c,s.d))=t;
}
This is c++14, but the missing bit for c++11 is easy:
template<STORE_ENUM e>
using store_type = typename std::tuple_element<(unsigned)e, std::tuple<int,char,long,bool>>::type;
template<STORE_ENUM e>
store_type<e> get( Store s ) {
return std::get<(unsigned)e>(std::make_tuple(s.a,s.b,s.c,s.d));
}
template<STORE_ENUM e>
void set( Store& s, store_type<e> v ){
std::get<(unsigned)e>(std::tie(s.a,s.b,s.c,s.d))=v;
}

Related

How can I code something like a switch for std::variant?

I have some var = std::variant<std::monostate, a, b, c> when a, b, c is some types.
How, at runtime, do I check what type var contains?
In the official documentation I found information that if var contains a type and I write std::get<b>(var) I get an exception. So I thought about this solution:
try {
std::variant<a>(var);
// Do something
} catch(const std::bad_variant_access&) {
try {
std::variant<b>(var);
// Do something else
} catch(const std::bad_variant_access&) {
try {
std::variant<c>(var);
// Another else
} catch (const std::bad_variant_access&) {
// std::monostate
}
}
}
But it's so complicated and ugly! Is there a simpler way to check what type std::variant contains?
std::visit is the way to go:
There is even overloaded to allow inlined visitor:
// helper type for the visitor #4
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
// explicit deduction guide (not needed as of C++20)
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
and so:
std::visit(overloaded{
[](std::monostate&){/*..*/},
[](a&){/*..*/},
[](b&){/*..*/},
[](c&){/*..*/}
}, var);
To use chained if-branches instead, you might used std::get_if
if (auto* v = std::get_if<a>(var)) {
// ...
} else if (auto* v = std::get_if<b>(var)) {
// ...
} else if (auto* v = std::get_if<c>(var)) {
// ...
} else { // std::monostate
// ...
}
The most simple way is to switch based on the current std::variant::index(). This approach requires your types (std::monostate, A, B, C) to always stay in the same order.
// I omitted C to keep the example simpler, the principle is the same
using my_variant = std::variant<std::monostate, A, B>;
void foo(my_variant &v) {
switch (v.index()) {
case 0: break; // do nothing because the type is std::monostate
case 1: {
doSomethingWith(std::get<A>(v));
break;
}
case 2: {
doSomethingElseWith(std::get<B>(v));
break;
}
}
}
If your callable works with any type, you can also use std::visit:
void bar(my_variant &v) {
std::visit([](auto &&arg) -> void {
// Here, arg is std::monostate, A or B
// This lambda needs to compile with all three options.
// The lambda returns void because we don't modify the variant, so
// we could also use const& arg.
}, v);
}
If you don't want std::visit to accept std::monostate, then just check if the index is 0. Once again, this relies on std::monostate being the first type of the variant, so it is good practice to always make it the first.
You can also detect the type using if-constexpr inside the callable. With this approach, the arguments don't have to be in the same order anymore:
void bar(my_variant &v) {
std::visit([](auto &&arg) -> my_variant {
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<std::monostate, T>) {
return arg; // arg is std::monostate here
}
else if constexpr (std::is_same_v<A, T>) {
return arg + arg; // arg is A here
}
else if constexpr (std::is_same_v<B, T>) {
return arg * arg; // arg is B here
}
}, v);
}
Note that the first lambda returns void because it just processes the current value of the variant. If you want to modify the variant, your lambda needs to return my_variant again.
You could use an overloaded visitor inside std::visit to handle A or B separately. See std::visit for more examples.
You can use standard std::visit
Usage example:
#include <variant>
#include <iostream>
#include <type_traits>
struct a {};
struct b {};
struct c {};
int main()
{
std::variant<a, b, c> var = a{};
std::visit([](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, a>)
std::cout << "is an a" << '\n';
else if constexpr (std::is_same_v<T, b>)
std::cout << "is a b" << '\n';
else if constexpr (std::is_same_v<T, c>)
std::cout << "is a c" << '\n';
else
std::cout << "is not in variant type list" << '\n';
}, var);
}
Well, with some macro magic, you can do something like:
#include <variant>
#include <type_traits>
#include <iostream>
#define __X_CONCAT_1(x,y) x ## y
#define __X_CONCAT(x,y) __X_CONCAT_1(x,y)
template <typename T>
struct __helper { };
// extract the type from a declaration
// we use function-type magic to get that: typename __helper<void ( (declaration) )>::type
// declaration is "int &x" for example, this class template extracts "int"
template <typename T>
struct __helper<void (T)> {
using type = std::remove_reference_t<T>;
};
#define variant_if(variant, declaration) \
if (bool __X_CONCAT(variant_if_bool_, __LINE__) = true; auto * __X_CONCAT(variant_if_ptr_, __LINE__) = std::get_if<typename __helper<void ( (declaration) )>::type>(&(variant))) \
for (declaration = * __X_CONCAT(variant_if_ptr_, __LINE__); __X_CONCAT(variant_if_bool_, __LINE__); __X_CONCAT(variant_if_bool_, __LINE__) = false)
#define variant_switch(variant) if (auto &__variant_switch_v = (variant); true)
#define variant_case(x) variant_if(__variant_switch_v, x)
int main() {
std::variant<int, long> v = 12;
std::variant<int, long> w = 32l;
std::cout << "variant_if test" << std::endl;
variant_if(v, int &x) {
std::cout << "int = " << x << std::endl;
}
else variant_if(v, long &x) {
std::cout << "long = " << x << std::endl;
}
std::cout << "variant_switch test" << std::endl;
variant_switch(v) {
variant_case(int &x) {
std::cout << "int = " << x << std::endl;
variant_switch (w) {
variant_case(int &x) {
std::cout << "int = " << x << std::endl;
}
variant_case(long &x) {
std::cout << "long = " << x << std::endl;
}
}
};
variant_case(long &x) {
std::cout << "long = " << x << std::endl;
variant_switch (w) {
variant_case(int &x) {
std::cout << "int = " << x << std::endl;
}
variant_case(long &x) {
std::cout << "long = " << x << std::endl;
}
}
};
}
return 0;
}
I tested this approach with GCC and Clang, no guarantees for MSVC.

Selecting a method using different enable_if conditions

I want to write a generic validate function. So i tried writing a meta program.
But it does not gets compiled, and rightly so. Can anyone tell me a way to achieve it.
I am posting my sample code. There can be 3 or more types of structs (here A, B, C), some having a particular type of header, another having other type of header and some even not having a header. So i want to write a program which correctly choose the required function (here f1(), f2() to validate a struct header. I don't want to use Boost Hana or any other reflection library.
#include <iostream>
using namespace std;
struct Header
{
int i;
};
struct OrderHeader
{
int i; int j;
};
struct A
{
Header header;
int val;
};
struct B
{
OrderHeader order_header;
int val;
int c;
};
struct C
{
int val;
int c;
};
bool f1(Header h)
{
return h.i == 1 ? true : false;
}
bool f2(OrderHeader oh)
{
return (oh.i == 1 and oh.j == 1) ? true : false;
}
template<typename St, typename = enable_if_t<is_same_v<decltype(St::header), Header>>>
using v1 = bool;
template<typename St, typename = enable_if_t<is_same_v<decltype(St::order_header), OrderHeader>>>
using v2 = bool;
template<typename St>
bool validate(St s)
{
if constexpr(is_same_v<v1<St>, bool>)
{
return f1(s.header);
}
else if constexpr(is_same_v<v2<St>, bool>)
{
return f2(s.order_header);
}
return true;
}
int main(int argc, char** argv)
{
A at{1,1};
A af{};
C c{};
B b{};
cout << boolalpha << validate(at) << endl;
cout << boolalpha << validate(af) << endl;
cout << boolalpha << validate(b) << endl;
cout << boolalpha << validate(c) << endl;
return 0;
}
if constexpr can be a means for partial compilation, but the condition inside if must always be compilable. In your case v1<St> and v2<St> only exist when St is of the right type, hence the errors.
You can use specialization of variable templates instead, e.g. like this
template<typename, typename = void>
constexpr bool is_v1 = false;
template<typename St>
constexpr bool is_v1<St, enable_if_t<is_same_v<decltype(St::header), Header>>> = true;
template<typename, typename = void>
constexpr bool is_v2 = false;
template<typename St>
constexpr bool is_v2<St, enable_if_t<is_same_v<decltype(St::order_header), OrderHeader>>> = true;
template<typename St>
bool validate(St s)
{
if constexpr (is_v1<St>)
{
return f1(s.header);
}
else if constexpr (is_v2<St>)
{
return f2(s.order_header);
}
return true;
}
Now is_v1<St> and is_v2<St> always return some value (either true or false), and the code should compile1.
1 There's also a typo in f2(): oh.i == 1 and oh.j == 1 should be oh.i == 1 && oh.j == 1.
Also note h.i == 1 ? true : false is tautologous, just h.i == 1 is enough.

C++ How does this code work (enable_if constructor/method)?

I know these two topics have been discussed before, but I still don't have a clear idea of how enable of a constructor and enable of a method works.
Here is a nice clear example that I created.
#include <type_traits>
#include <string>
#include <iostream>
template<bool B> using EnableConstructorIf = typename std::enable_if<B, int>::type;
template<bool B, class T> using EnableMethodIf = typename std::enable_if<B,T>::type;
template <int N>
class MyClass {
public:
std::string s;
template<int M=N, EnableConstructorIf< (M<0) > = 0> MyClass() {
s = "Negative";
}
template<int M=N, EnableConstructorIf< (M==0) > = 0> MyClass() {
s = "Zero";
}
template<int M=N, EnableConstructorIf< (M>0) > = 0 > MyClass() {
s = "Positive";
}
template<int M=N> EnableMethodIf< (M<0), int> getSign() {
return -1;
}
template<int M=N> EnableMethodIf< (M==0), int> getSign() {
return 0;
}
template<int M=N> EnableMethodIf< (M>0), int> getSign() {
return +1;
}
};
int main(int argc, char *argv[])
{
using namespace std;
MyClass<-5> a;
MyClass<0> b;
MyClass<100> c;
cout << "a.string = " << a.s <<" ->"<< a.getSign() << endl;
cout << "b.string = " << b.s <<" ->"<< b.getSign() << endl;
cout << "c.string = " << c.s <<" ->"<< c.getSign() << endl;
return 0;
}
It compiles and produces the following output, as expected. But how does it work?
a.string = Negative ->-1
b.string = Zero ->0
c.string = Positive ->1

Reading a WORD variable from a CArchive and casting to int at the same time

This might sound basic but:
WORD wSong = 0;
CArchive ar;
...
ar >> wSong;
m_sPublicTalkInfo.iSongStart = static_cast<int>(wSong);
At the moment I read the WORD into a specific variable and the cast it.
Can I read it in and cast at the same time?
Please note I can't serialize a int. It must be a WORD and cast to int.
Or
ar >> wSong;
m_sPublicTalkInfo.iSongStart = static_cast<int>(wSong);
I don't think there is a direct way. You could implement a helper function:
template <typename T, typename U>
T readAndCast (CArchive& ar) {
U x;
ar >> x;
return static_cast<T> (x);
}
m_sPublicTalkInfo.iSongStart = readAndCast<int, WORD>(ar);
It might be better to use the fixed-width integer types in your program, i.e. perhaps int_least16_t instead of int to be sure the type has the right size. WORD is fixed to 16bit, but int isn't. Also, WORD is unsigned and int isn't, so there could be an overflow during casting.
This is a example of how you could create a wrapper if you want the serialize syntax to remain consistent. It's designed to work with integrals and MFC unsigned types only.
#include <iostream>
#include <cstdint>
#include <sstream>
#include <type_traits>
// Fake the MFC types
using BYTE = std::uint8_t;
using WORD = std::uint16_t;
using DWORD = std::uint32_t;
using QWORD = std::uint64_t;
template<typename T>
struct is_valid_save_type : std::bool_constant<
std::is_same_v<BYTE, T> ||
std::is_same_v<WORD, T> ||
std::is_same_v<DWORD, T> ||
std::is_same_v<QWORD, T>
> {};
template<typename T>
struct is_valid_load_type : is_valid_save_type<T> {};
// Saves type T as a SaveType
template<typename T, typename SaveType>
struct save_as_type
{
explicit save_as_type(T value) : value(value) {}
explicit operator SaveType() const
{
return static_cast<SaveType>(value);
}
private:
T value;
// This class only works with integrals
static_assert(std::is_integral_v<T>);
// SaveType should be BYTE/WORD/DWORD/QWORD only
static_assert(is_valid_save_type<SaveType>::value);
};
// Loads type T as a LoadType
template<typename T, typename LoadType>
struct load_as_type
{
explicit load_as_type(T& value) : value_(value) {}
load_as_type& operator=(LoadType rhs)
{
value_ = rhs;
return *this;
}
private:
T& value_;
// T should be an integral
static_assert(std::is_integral_v<T>);
// T must be non-constant
static_assert(!std::is_const_v<T>);
// LoadType should be BYTE/WORD/DWORD/QWORD only
static_assert(is_valid_load_type<LoadType>::value);
};
class CArchive;
// Make the above types serializable
template<typename T, typename SaveType>
CArchive& operator<<(CArchive& ar, save_as_type<T, SaveType> const& s)
{
ar << static_cast<SaveType>(s);
}
template<typename T, typename LoadType>
CArchive& operator>>(CArchive& ar, load_as_type<T, LoadType> l)
{
LoadType t{};
ar >> t;
l = t;
}
// Use the following two functions in your code
template<typename SaveType, typename T>
save_as_type<T, SaveType> save_as(T const& t)
{
return save_as_type<T, SaveType>{ t };
}
template<typename LoadType, typename T>
load_as_type<T, LoadType> load_as(T& t)
{
return load_as_type<T, LoadType>{ t };
}
// Prevent loading into temporaries; i.e. load_as<BYTE>(11);
template<typename T, typename LoadType>
load_as_type<T, LoadType> load_as(const T&& t) = delete;
// Fake MFC Archive
class CArchive
{
public:
CArchive& operator<<(int i)
{
std::cout << "Saving " << i << " as an int\n";
return *this;
}
CArchive& operator<<(BYTE b)
{
std::cout << "Saving " << (int)b << " as a BYTE\n";
return *this;
}
CArchive& operator<<(WORD w)
{
std::cout << "Saving " << (int)w << " as a WORD\n";
return *this;
}
CArchive& operator<<(DWORD d)
{
std::cout << "Saving " << (int)d << " as a DWORD\n";
return *this;
}
CArchive& operator>>(int& i)
{
std::cout << "Loading as an int\n";
return *this;
}
CArchive& operator>>(BYTE& b)
{
std::cout << "Loading as a BYTE\n";
return *this;
}
CArchive& operator>>(WORD& w)
{
std::cout << "Loading as a WORD\n";
return *this;
}
CArchive& operator>>(DWORD& d)
{
std::cout << "Loading as a DWORD\n";
return *this;
}
};
int main()
{
CArchive ar;
int out_1 = 1;
int out_2 = 2;
int out_3 = 3;
int out_4 = 4;
ar << out_1 <<
save_as<BYTE>(out_2) <<
save_as<WORD>(out_3) <<
save_as<DWORD>(out_4);
std::cout << "\n";
int in_1 = 0;
int in_2 = 0;
int in_3 = 0;
int in_4 = 0;
ar >> in_1 >>
load_as<BYTE>(in_2) >>
load_as<WORD>(in_3) >>
load_as<DWORD>(in_4);
return 0;
}
Output:
Saving 1 as an int
Saving 2 as a BYTE
Saving 3 as a WORD
Saving 4 as a DWORD
Loading as an int
Loading as a BYTE
Loading as a WORD
Loading as a DWORD

Checking for a specific nested type/tag with boost hana

Having fun with boost::hana. I wish to check for a specific nested type that acts like a tag in another type, so I borrow from hana::when_valid example and defined a class is_S along with its SFINAE-enabled specialization:
#include <iostream>
#include <boost/hana/core/when.hpp>
namespace hana = boost::hana;
#define V(x) std::cout << x << std::endl
struct S_tag { };
struct S {
using tag = S_tag;
};
struct T {
using tag = int;
};
template< typename T, typename = hana::when< true > >
struct is_S {
static constexpr bool value = false;
};
template< typename T >
struct is_S< T, hana::when_valid< typename T::tag > > {
static constexpr bool value = std::is_same<
typename T::tag, S_tag >::value;
};
int main () {
std::cout << "is_S ( S { }) = "; V ((is_S< S >::value));
std::cout << "is_S ( T { }) = "; V ((is_S< T >::value));
std::cout << "is_S (float { }) = "; V ((is_S< float >::value));
return 0;
}
This prints:
$ clang++ -std=c++1z sfinae.cpp && ./a.out | c++filt
is_S ( S { }) = 1
is_S ( T { }) = 0
is_S (float { }) = 0
Is there a simpler/shorter/more succinct way of writing the same check, in keeping with value-type computation of hana philosophy?
Here's what I might write:
#include <boost/hana.hpp>
#include <iostream>
namespace hana = boost::hana;
struct S_tag { };
struct S { using tag = S_tag; };
struct T { using tag = int; };
auto tag_of = [](auto t) -> hana::type<typename decltype(t)::type::tag> {
return {};
};
auto is_S = [](auto t) {
return hana::sfinae(tag_of)(t) == hana::just(hana::type<S_tag>{});
};
int main() {
std::cout << "is_S ( S { }) = " << is_S(hana::type<S>{})() << std::endl;
std::cout << "is_S ( T { }) = " << is_S(hana::type<T>{})() << std::endl;
std::cout << "is_S (float { }) = " << is_S(hana::type<float>{})() << std::endl;
}
I woukd be tempted by:
template<class...T>
constexpr std::integral_constant<bool,false> is_S(T const&...){ return {}; }
template<class T>
constexpr
std::integral_constant<bool,std::is_same<typename T::tag,S_tag>{}>
is_S(T const&){ return {}; }