Can I use variadic templates without using the template parameters as function parameters?
When I use them, it compiles:
#include <iostream>
using namespace std;
template<class First>
void print(First first)
{
cout << 1 << endl;
}
template<class First, class ... Rest>
void print(First first, Rest ...rest)
{
cout << 1 << endl;
print<Rest...>(rest...);
}
int main()
{
print<int,int,int>(1,2,3);
}
But when I don't use them, it doesn't compile and complains about an ambiguity:
#include <iostream>
using namespace std;
template<class First>
void print()
{
cout << 1 << endl;
}
template<class First, class ... Rest>
void print()
{
cout << 1 << endl;
print<Rest...>();
}
int main()
{
print<int,int,int>();
}
Unfortunately the classes I want to give as template parameters are not instantiable (they have static functions that are called inside of the template function). Is there a way to do this?
template<class First> // 1 template parameter
void print()
{
cout << 1 << endl;
}
#if 0
template<class First, class ... Rest> // >=1 template parameters -- ambiguity!
void print()
{
cout << 1 << endl;
print<Rest...>();
}
#endif
template<class First, class Second, class ... Rest> // >=2 template parameters
void print()
{
cout << 1 << endl;
print<Second, Rest...>();
}
Make it a type.
template <typename... Ts>
struct print_impl;
template <typename T>
struct print_impl<T> {
static void run() {
std::cout << 1 << "\n";
}
};
template <typename T, typename... Ts>
struct print_impl<T, Ts...> {
static void run() {
std::cout << 1 << "\n";
print_impl<Ts...>::run();
}
};
template <typename... Ts>
void print() {
print_impl<Ts...>::run();
}
int main() {
print<int, int, int>();
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With