DarthRubik
DarthRubik

Reputation: 3975

Implicit Type Conversion: Not Member of Class or Struct

I am trying to find a more elegant way to read and write structs than to convert them to a void pointer and then pass the size into the function like this:

void write(void* value, size_t length);    //Write is some random write function

Type var;
write((void*)var,sizeof(Type));  

So I was trying to create a method to convert any type implicitly to a struct like the following:

struct VoidPtrReplacement{
  uint8_t* bytes;
  size_t size;
};

And then I could (provided I could find a way to implicitly convert to this type from any other type) create nice read and write functions like this:

void write(VoidPtrReplacement* value);

Type var;
write(var);

Unfortunately the only way I could find to convert to this type from any other type would be to make VoidPtrReplacement a templated struct. I don't want to this because then any write functions that I create that use this struct have to be templated also.

So my question is: can I create an implicit conversion function that is not part of any struct or class (or if there is a better way to do this)?

Upvotes: 4

Views: 102

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118340

You don't need a templated struct, just a templated constructor. Something like this:

#include <iostream>
#include <vector>

struct VoidPtrReplacement{
    const unsigned char *bytes;
    size_t size;

    template<typename T>
    VoidPtrReplacement(T &&t)
        : bytes(reinterpret_cast<unsigned char *>(&t)),
          size(sizeof(T))
    {
    }
};

void write(const VoidPtrReplacement &p)
{
    std::cout << "Write: " << (void *)p.bytes << ", " << p.size << " bytes"
          << std::endl;
}

class Foo {
    int i=4;
};

class Bar {
    char c=0;
    int b=3;
};

int main()
{
    Foo foo;
    Bar bar;

    std::cout << "Address of foo: " << &foo << std::endl;
    std::cout << "Address of bar: " << &bar << std::endl;

    write(foo);
    write(bar);
}

Sample output:

Address of foo: 0x7ffd5eba4c80
Address of bar: 0x7ffd5eba4c60
Write: 0x7ffd5eba4c80, 4 bytes
Write: 0x7ffd5eba4c60, 8 bytes

Upvotes: 2

Related Questions