I am currently experimenting with variadic templates, as I am trying to use a variadic class template for a project I am working on. I want the class to accept a list of integers which will be used to create other elements of the class. Initially, I was using a template constructor function to take an array of integers. However, I ran into problems linking the code. I figured out an alternate way of solving my problem using a variadic class template to take the list of integers, but I am curious if this code is considered bad c++ (I haven't written C++ in a while and this feels very hacky). Anyway, here is the test code I have written, which compiles and works as expected:
template<int...structure>
class testClass{
public:
testClass(){
std::size_t size = sizeof...(structure);
std::cout << size << '\n';
int arr[]{ structure... };
for (int i = 0; i < size; i++)
std::cout << arr[i] << '\n';
}
};
int main() {
testClass<1, 2, 3> c;
}
As expected, the code outputs:
3
1
2
3
Is there anything wrong with this solution? I have been searching online and no one seems to be using variadic templates in this way.
Thanks in advance for the input.
There is nothing wrong or hacky with your solution, it is just a trade off. With your solution, you immediately initialize the array so it has the best performance. With the std::initializer_list
solutions they have to default the members of the array and then copy which is more work.
On the flip side that means you can only construct your object at compile time, while the std::initializer_list
version can be initialized at run time.
Another issue is storing them in a container. You can't store different testClass
's in a std::vector
since different template parameters mean they are different type and vector only stores a single element type. If you took a std::initializer_list
then testClass
wouldn't be a template and you can store different ones in the same vector
.