如何使模板函数像 R f<void(int)>(args...)

how to make a template function like R f<void(int)>(args...)

本文关键字:int 何使模 gt args void 函数 lt      更新时间:2023-10-16

现在我想创建一个看起来像f<void(int)>(args...)的函数,我的代码是:

template<typename T>
struct A{};
template<typename F>
A<F> f4();
template<typename R,typename... Args>
A<R(Args...)> f4<R(Args...)>() {
return A<R(Args...)>();
}

但它不起作用并且 vs 给出错误 C2768

我该怎么做?

您不能部分专用化函数模板; 类模板可以。

例如
// primary template
template<typename F>
struct f4_s {
static A<F> f4() {
return A<F>();
}
};
// partial specialization
template<typename R,typename... Args>
struct f4_s<R(Args...)> {
static A<R(Args...)> f4() {
return A<R(Args...)>();
}
};
template<typename T>
auto f4() {
return f4_s<T>::f4();
}

然后

f4<int>();           // call the primary version
f4<int(int,char)>(); // call the specialization version

或者使用函数模板应用重载。

template<typename F>
std::enable_if_t<!std::is_function_v<F>, A<F>> f4() {
return A<F>();
}    
template<typename F>
std::enable_if_t<std::is_function_v<F>, A<F>> f4() {
return A<F>();
}

然后

f4<int>();           // call the 1st overload
f4<int(int,char)>(); // call the 2nd overload

相关文章: