下一个代码有问题:
#include <iostream>
#include <functional>
using namespace std;
template<typename... Args>
inline double foo(function<double (Args...)> fun, Args... args) {
return fun(args...);
}
template<typename... Args, typename... ArgsTmp>
double foo(function<double (Args...)> fun, ArgsTmp... args) {
return foo(fun, 1., args...);
}
int main() {
function<double (double, double, double)> fun = [&](double x, double y, double z) -> double {
return x+y+z;
};
cout << foo(fun) << endl;
}
当我用gcc编译时,一切都很好。但是,如果我尝试使用intel或nvcc-7.5(实际上是我的目标)进行编译,则会收到以下错误:
more than one instance of overloaded function "foo" matches the argument list:
function template "double foo(std::vector<limits, std::allocator<limits>>, std::function<double (Args...)>, Args...)"
function template "double foo(std::vector<limits, std::allocator<limits>>, std::function<double (Args...)>, ArgsTmp...)"
argument types are: (std::vector<limits, std::allocator<limits>>, std::function<double (double, double, double)>, double, double, double)
...
1 error
有什么方法可以让编译器明确地知道,当
Args==ArgsTmp
(在第二个模板中)时,应拒绝以下foo()
的增加? 最佳答案
您可以尝试SFINAE和enable_if
template<typename... Args, typename... ArgsTmp>
std::enable_if_t<!std::is_same<std::tuple<Args...>,
std::tuple<ArgsTmp...>>::value,
double>
foo(function<double (Args...)> fun, ArgsTmp... args) {
return foo(fun, 1., args...);
}
关于c++ - C++可变参数模板:gcc和nvcc/intel中的不同优先级,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33550295/