Aditya Kumar Praharaj
Aditya Kumar Praharaj

Reputation: 309

Take pointer with its datatype as a parameter

I need process an array whose data-type is either float64_t or uint32_t. I want to make a function such that the pointer to the given array can be taken as a parameter to the function in this way:

void func_name(array_type* ptr_name, int count, data_type x)
//x can be float64_t or uint32_t

As you can see, beforehand I don't know the data-type of the pointer. How do I approach this problem in C++?

Upvotes: 0

Views: 91

Answers (2)

Pandrei
Pandrei

Reputation: 4951

You can create a template - as already suggested by jrok

template<typename T>
void func(T* ptr, int count);

This way you will be able to pass a pointer to ANY data type to your function. Essentially a template a template expands into a function for each data type you use it with, at compile time.

if you however you want to over-complicate things, for obfuscation's sake let's say, you could do the following:

  void func(void* ptr, int count);

have you function take a generic pointer- you will have to do a reinterpret cast when calling the function to convert your pointer to a void*, and inside the function to convert it to which ever pointer type you like; and your count will be the number of bytes you want to read.

But I'm sure you will appreciate the simplicity and transparency of the first solution ( the template).

Upvotes: 1

jrok
jrok

Reputation: 55395

You can overload the functions:

void func(float64_t* ptr, int count);
void func(uint32_t* ptr, int count);

or make a function template:

template<typename T>
void func(T* ptr, int count);

The "data-type" (sic) of an array (and pointers) is a part of its type, you don't need to do anything special. Whichever approach you decide to take, the compiler will figure out for you which function to call (or what T will be when instantiating a template).

template<typename T>
void func(T* ptr, int count) { }

int main()
{
    float f_arr[42] = {};
    int i_arr[84] = {};

    func(f_arr, 42);  // instantiates func with T = float
    func(i_arr, 84);  // instantiates func with T = int
}

Upvotes: 6

Related Questions