简体   繁体   English

专门化模板化数据类型的模板

[英]Specialize template of templated data type

I have this situation: 我有这种情况:

#include <vector>

template<typename T>
T f() { return T(); }

template<>
template<typename T>
std::vector<T> f<std::vector<T>>() {
    return { T() };
}

int main(){
    f<std::vector<int>>();
}

I'm trying to specialize the template for std::vector<T> , but I'm getting this error: 我正在尝试专门为std::vector<T>模板,但我收到此错误:

error: too many template-parameter-lists

std::vector<T> f<std::vector<T>>() {

How can I specialize for std::vector<T> ? 我怎样才能专门研究std::vector<T>

There's no such thing as partially specialized function templates. 没有部分专门的功能模板这样的东西。 What you are doing is creating a new template, so the correct syntax would be: 你正在做的是创建一个新模板,所以正确的语法是:

template<typename T>
std::vector<T> f() {
    return { T() };
}

This overloads the function name f and the two templates are independent. 这会重载函数名称f并且这两个模板是独立的。 But by having both overloads will make almost all calls to f ambiguous including the one example in your main() . 但是,通过让两个重载都会使几乎所有的f都变得模糊,包括main()的一个例子。

EDIT: 编辑:

Had you removed the template<> line which would be invalid for class partial specializations too then clang generates more helpful error message: 如果您删除了对类部分特化无效的template<>行,那么clang会生成更多有用的错误消息:

error: non-class, non-variable partial specialization f<std::vector<T,std::allocator<_Tp1> > > is not allowed 错误:不允许非类,非变量部分特化f<std::vector<T,std::allocator<_Tp1> > >

 std::vector<T> f<std::vector<T>>() { 

If a problem is X, and a solution is Y, then usually specialization of function templates is Z. That's when specialization is possible anyway. 如果问题是X,并且解决方案是Y,那么通常功能模板的专业化是Z.那时无论如何都可以进行专业化。 You can't partially specialize function templates, only overload them. 您不能部分专门化功能模板,只能重载它们。

A solution here would be to use a helper. 这里的解决方案是使用帮助器。 A class template, which you can specialize, that will do the work. 一个可以专门化的类模板, 可以完成工作。 Meanwhile the function template only forwards to it. 同时功能模板只转发给它。

namespace detail {
    template<typename T>
    struct f {
        static T work() { return T(); }
    };

    template<typename T>
    struct f<std::vector<T>> {
        static std::vector<T> work() { return {T()}; }
    };
}

template<typename T>
T f() { return detail::f<T>::work(); }

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

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