Reputation: 109
I am using a variadic template function where the function parameters isn't the templated types.
I got a compilation error:
Error C2668 '_TailHelper': ambiguous call to overloaded function
Here it is the code snippet.
template <typename HEAD>
void _TailHelper(int) {
std::cout << typeid(HEAD).name() << std::endl;
}
template <typename HEAD, typename ... TAILS>
void _TailHelper(int x) {
_TailHelper<HEAD>(x);
_TailHelper<TAILS...>(x);
}
int main(){
_TailHelper<int,double>(2);
}
Upvotes: 2
Views: 605
Reputation: 217245
As alternative to recursion, you might "loop" over your variadic:
In C++17:
template <typename... Ts>
void PrintTypes() {
((std::cout << typeid(Ts).name() << std::endl), ...);
}
In previous version, it is less elegant, and you might use some trick as:
template <typename... Ts>
void PrintTypes() {
const int dummy[] = {0, ((std::cout << typeid(Ts).name() << std::endl), 0)...};
static_cast<void>(dummy); // Avoid warning for unused variable
}
Upvotes: 0
Reputation: 10979
Both overloads match with single template argument, so you have to disable one. For example like that:
#include <iostream>
#include <typeinfo>
template <typename T>
void TailHelper(int) {
std::cout << typeid(T).name() << std::endl;
}
template <typename HEAD, typename ... TAILS>
typename std::enable_if<(sizeof...(TAILS) != 0)>::type
TailHelper(int x) {
TailHelper<HEAD>(x);
TailHelper<TAILS...>(x);
}
int main() {
TailHelper<int,double>(2);
}
Upvotes: 5
Reputation: 48
The ambiguous call comes from this line:
_TailHelper<HEAD>(x);
this call matches both functions the first one, and the second function which its second parameter can refer to zero or more template parameters.
Upvotes: 0