【问题标题】:how to make a template function like R f<void(int)>(args...)如何制作像 R f<void(int)>(args...) 这样的模板函数
【发布时间】:2019-12-03 03:10:31
【问题描述】:

现在我想创建一个看起来像 f&lt;void(int)&gt;(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

我该怎么做?

【问题讨论】:

  • 如果您可以尝试更具体地说明您要在这里实现的目标,这将有所帮助。

标签: c++ c++11 templates c++14 c++17


【解决方案1】:

你不能部分专门化函数模板;类模板即可。例如

// 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

LIVE

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

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

LIVE

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    相关资源
    最近更新 更多