Home Class with template member variable and functions
Reply: 1

Class with template member variable and functions

SupaDupa Published in 2017-12-07 20:31:56Z

I'm trying to create something like this:

// The code doesn't work, it should just be a pseudo to help understand what i'm trying to create
template <typename Variable>
class Address
    unsigned int A_Address;
    Variable A_Type;

    void Set(A_Type value)
        *((A_Type*)A_Address) = value;

    A_Type Get()
        return *((A_Type*)A_Address);

Address address_1 = new Address<float/*type*/>(0x00000000/*address in memory*/);
float value_1 = address_1.Get();

Address address_2 = new Address<int/*type*/>(0x00000000/*address in memory*/);
int value_2 = address_2.Get();

So i want to be able to define objects like Address obj_1, obj_2; and then Initialize them later with a type and an address. Then the Get() method should return it's current value in memory and the Set() method should set that value in memory. I couldn't figure out how to not do Address<float> obj_1; and instead using Address obj_1; and initializing it later. Hope you understood what i'm trying to do and could let me know if it's possible and if so maybe help me out or point me in the right direction. Thanks in advance!

Labonneguigue Reply to 2017-12-07 21:38:52Z

I'm not really dealing with your address mangling but what you want can be done that way :

struct Address
Address(unsigned int addr)
: A_Address(addr)

unsigned int A_Address;

template <typename T>
void Set(T value)
    *((T*)A_Address) = value;

template <typename T>
T Get()
    return *((T*)A_Address);

And you can use it that way

Address address(0x00000000);  //won't work because of virtual addressing
std::cout << address.Get<float>();

std::cout << address.Get<double>();

Be careful when you handle addresses that way, very error-prone. Have a look over there:

Pass a hex address to a Pointer Variable

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301351 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO