Is there a way in C++ to create a templated class that takes any number of arguments in the constructor and can get those when needed?
Example:
#include <string>
template<size_t Size, typename... Types>
class Container
{
public:
Container(Types... args)
{
// add checks to see if Size = no args
}
void get(Types&... args)
{
// getter method
}
};
int main()
{
Container<3, int, double, std::string> container(10, 2.5, "smth");
int a{};
double b{};
std::string c {};
container.get(a, b, c);
// expect a = 10, b = 2.5, c = "smth"
return 0;
}
Yes, a solution to your problem already exists in the form of
std::tuple:You can implement a container that wraps
std::tuple, but it doesn't really provide any utility thatstd::tupledoesn't yet, so we can use it directly:Keep in mind that outside of generic programming, you're almost always better off creating your own
struct, with meaningful names for the type and the members.