Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is passing literal string as template parameter not good

I’m working on a c++ project and I just defined a function as below:

template<typename... Args>
void func(Args&&... args) {}

Then, call it like this:

func("abc"); // char[4]?
func("de");  // char[3]?

My question is if the compiler will deduce two independent functions, one is for char[4] and the other is for char[3]? If I call many func with const char* as above, the compiler will generate many independent functions?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is this stupid? Should I avoid this?

In fact, func("abc") and func(std::string("abc")); are exactly the same for me.

So should I call this function like func(std::string("abc")); and func(std::string("de")); so that the compiler will generate only one function as void func(const std::string&);

BTW, My project is developed with C++14.

>Solution :

My question is if the compiler will deduce two independent functions, one is for char[4] and the other is for char[3]?

It will.

If I call many func with const char* as above, the compiler will generate many independent functions?

You don’t call func with const char*. If you did call func with only const char* then there would be only one instantiation of the function template.

You call the function with const char[4] and const char[3] which do cause separate instantiations. There will be an instantiation for each unique sets of template arguments.

Is this stupid? Should I avoid this?

Depends on use case. In many cases, the optimiser simply expands all calls inline and the instantiations won’t leave any trace of their theoretical existance in the generated assembly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading