'Is passing literal string as template parameter not good [closed]
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?
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 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eerorika |
