Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method chaining from namespace

Sorry if this question causes any confusion, I am looking to implement this and do not know the right way to approach such a thing.

For one of my projects I want to implement method chaining. I want to incorporate the following functions:

.toVector()
.toArray()
.toBool()
...

I have thought about placing these inside a namespace, e.g:

namespace Misc {
   template<typename T, typename Inverse>

   vector<T> toVector(Inverse begin, Inverser end) {
      // ...
      // ..
   }

   // ...
   // ...
}

This is because there could be multiple classes, these classes MIGHT be able to use these functions, so therefore, it has to be OO rather than implementing each function again and again in different classes.

Let's say I have the following class Wav which reads in the data contained in a wav file:

class Wav {
   public:
     Wav();
     Wav(string theFileName);
     void getWaveData();
  protected:
     vector<double> data;
};

data is explicitly stored as a vector inside of the class.

In my main I want to be able to do the following:

int main()
{
    Wav wave("file.wav");

    int* data = wave.getWaveData().toArray(); // Method chaining to store as an array
}

I do not know whether or not this would be possible and if so how I would approach this without implementing all of the Misc functions over and over again inside each of the classes. Is there a way to communicate between the namespace and the class without having to include all of the functions over and over again?

I hope someone has a suggestion and any questions I will try to answer.

EDIT:

I have the written the following function:

template<typename T, typename Inverse>
T* toArray(Inverse begin, Inverse end)
{
size_t size = distance(begin, end);
auto pos = 0;

T* tmp = new T[size];

for(auto i = begin; i != end; i++)
{
    tmp[pos] = *i;
    pos++;
}
return tmp;
}

And if I have another function:

void process()
{

}

What would I therefore need to put inside the params of process in order to accept the following:

int* data = process(toArray<int>( std::begin(vals), std::end(vals) );

This is the thing that is confusing me the most?

like image 773
Phorce Avatar asked Nov 02 '22 17:11

Phorce


1 Answers

Regarding your new function:

In order to be able to call the process method below

int* data = process(toArray<int>( vals.begin(), vals.end()) );

the parameter for the process method should match the return type of the toArray method. Perhaps you can templatize the process method too as below.

template<typename T>
T* process(T* t)
{
   //more code here 
   return t;
}

After adding the process method as above, the call to process will compile, but you will have to make the implementation of the process method generic enough to deal with different return types from other methods like toArray.

like image 129
facthunter Avatar answered Nov 15 '22 03:11

facthunter