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 ?
Generally, where you need an IN parameter, pass built-in types by value, and other types by reference to
const, i.e.,With this definition, chances are that the compiler+linker will optimize things so that there will be only one machine code version of
function.I was a bit surprised the first time I checked a simple small example program, that expressing it with compile time polymorphism (templating) produced smaller and more efficient code than expressing it with run time polymorphism!
Try it yourself, and if you’re as surprised as I once was, then Good! Otherwise, chances are that there’ll be no significant difference. But in some corner case you may find what in the old days was called “template code bloat”, and then it’s time to ignore it or measure whether it’s significant enough to do work on translating to run time polymorphism.
Now to your question,
No, it’s not impossible to transform the compile time polymorphism to efficient run time polymorphism, or to simply no polymorphism. Especially since you’re already passing a run-time size (which presumably is guaranteed smaller than the fixed size).
A safe way is to use
std::stringfrom the C++ standard library, header<string>. That involves dynamic allocation somewhere in the internals ofstd::string, done automatically for you, but affecting efficiency. But your code, containingchar[size] characters, was not valid C++, and that indicates beginner level, so chances are that your design was not chosen for any good reason — hence, do:Cheers & hth.,