简体   繁体   English

在可变参数模板函数中对重载函数的模糊调用

[英]Ambiguous call to overloaded function in variadic template function

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错误 C2668“_TailHelper”:对重载函数的调用不明确

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);
}

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);
}

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.此调用匹配第一个函数和第二个函数,其第二个参数可以引用零个或多个模板参数。

As alternative to recursion, you might "loop" over your variadic:作为递归的替代方法,您可以“循环”您的可变参数:

In C++17:在 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM