Yes, in C++ you can create a function template that accepts multiple arguments of the same type using template parameter packs along with type traits/static_asserts to enforce that all arguments are of the same type.
Here’s a few ways to do this, depending on what you're trying to accomplish:
✅ Option 1: Use Variadic Templates with Type Check
If you want a function template that accepts multiple arguments only if they are all of the same type, you can do this with a variadic template and a static assertion like so:
#include <type_traits>
#include <iostream>
template<typename T, typename... Args>
void func(T first, Args... args) {
static_assert((std::is_same_v<T, Args> && ...), "All arguments must be of the same type");
// Example operation
std::cout << "All arguments are of type: " << typeid(T).name() << '\n';
}
Usage:
func(1, 2, 3); // OK: all ints
func(1.0, 2.0, 3.5); // OK: all doubles
func(1, 2.0); // Error: int and double
✅ Option 2: Accept a std::initializer_list<T>
If the number of arguments is flexible and they’re all the same type, you can use std::initializer_list<T>.
#include <iostream>
#include <initializer_list>
template<typename T>
void func(std::initializer_list<T> args) {
for (auto& val : args) {
std::cout << val << " ";
}
std::cout << '\n';
}
Usage:
func({1, 2, 3}); // OK
func({1.0, 2.0, 3.5}); // OK
func({1, 2.0, 3}); // Narrowing warning or error
Note: All arguments must be convertible to T, and literal types must be explicitly typed to avoid narrowing issues.
✅ Option 3: Take a std::vector<T> or similar container
This is a more conventional and safe approach for run-time variability:
#include <vector>
#include <iostream>
template<typename T>
void func(const std::vector<T>& vec) {
for (const auto& val : vec) {
std::cout << val << " ";
}
std::cout << '\n';
}
Usage:
func(std::vector<int>{1, 2, 3});
func(std::vector<double>{1.5, 2.5});
Summary
| Approach | Description |
|---|
| Variadic template + static_assert | Most flexible; compile-time check on types |
initializer_list | Simple for same-type literals |
vector | Good if the caller already has a container |
Let me know which use case you have — compile-time checks, containers, etc. — and I can tailor a better example!