Why is passing this kind of variable-size parameter by valueimpossible ?

G

Good Guy

We have a structure like below:

template<size_t size>
class Container{
public:
char characters[size];
};

And we have a function like below:

template <size_t size>
void function(Container<size> input,size_t Size){
//all instances do exactly same thing and with regard to Size
that determines the size of object
}

Now in C++ for every value of size, a different instance of function
will be created and apparently that's not right in this case since all
instances do the same thing, to avoid this the first function
parameter should be a pointer(char * pointer) instead of an object so
that accepts any array with any size eliminating the need for function
to be templated, but I'm curious having a single function which
accepts a variable-size parameter like above that's not allowed by C++
is something impossible at all to implement and generate assembly for,
or somehow leads to an inefficient implementation in terms of speed/
memory ?
 
J

Jonathan Lee

We have a structure like below:

    template<size_t size>
    class Container{
     public:
      char characters[size];
    };

And we have a function like below:

    template <size_t size>
    void function(Container<size> input,size_t Size){
     //all instances do exactly same thing and with regard to Size
that determines the size of object
    }

Now in C++ for every value of size, a different instance of function
will be created and apparently that's not right in this case since all
instances do the same thing,

If that were true, why are you templating the function? The very act
of using templates signals to the compiler that different functions
are required.

If you cannot write a single function, I suppose you have your answer.
Either the template parameter "size", or the type "Container<size>"
is relevant to operation of the function. Hence, different functions.

(Keep in mind that, for example, Container<1> and Container<2> are
actually different types. So f(Container<1> a) and f(Container<2>)
cannot be the same function for basically the same reasons that
f(long a) and f(int a) cannot be the same function).

--Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,068
Latest member
MakersCBDIngredients

Latest Threads

Top