简体   繁体   English

如何使用模板类型专门化模板功能

[英]How to specialize template function with template types

Is it possible to specialize a template function for template types? 是否可以为模板类型专门化模板函数? I don't know if my terminology is correct, so I'll provide a simple sample with what I want to achieve: 我不知道我的术语是否正确,所以我将提供一个简单的样本,我想要实现的目标:

#include <vector>
#include <string>
#include <iostream>

template<typename T>
void f()
{
    std::cout << "generic" << std::endl;
}

template<>
void f<std::string>()
{
    std::cout << "string" << std::endl;
}

template<typename T>
void f<std::vector<T>>()
{
    std::cout << "vector" << std::endl;
}

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

    return 0;
}

This code doesn't compile. 此代码无法编译。 VS2013 gives me VS2013给了我

error C2995: 'void f(void)' : function template has already been defined 错误C2995:'void f(void)':已经定义了函数模板

on this function: 在这个功能上:

template<typename T>
void f<std::vector<T>>()
{
    std::cout << "vector" << std::endl;
}

How may I achieve this behavior? 我怎么能实现这种行为? It's very important to have type f(void) signature. 具有type f(void)签名非常重要。 Is this code falling into partial specialization for functions(forbidden in C++)? 这段代码是否属于函数的部分特化(在C ++中是禁止的)?

You can't partially specialize template function, but you can for template class. 您不能部分专门化模板功能,但您可以使用模板类。 So you can forward your implementation to a dedicated class. 因此,您可以将实现转发到专用类。 Following may help: ( https://ideone.com/2V39Ik ) 以下可能有所帮助:( https://ideone.com/2V39Ik

namespace details
{
    template <typename T>
    struct f_caller
    {
        static void f() { std::cout << "generic" << std::endl; }
    };

    template<>
    struct f_caller<std::string>
    {
        static void f() { std::cout << "string" << std::endl; }
    };

    template<typename T>
    struct f_caller<std::vector<T>>
    {
        static void f() { std::cout << "vector" << std::endl; }
    };
}

template<typename T>
void f()
{
    details::f_caller<T>::f();
}

Trying to be as close as possible to the original code is: 尝试尽可能接近原始代码:

#include <vector>
#include <string>
#include <iostream>

template<typename T>
struct f {
    void operator()()
    {
        std::cout << "generic" << std::endl;
    }
};

template<>
struct f<std::string> {
    void operator()()
    {
        std::cout << "string" << std::endl;
    }
};

template<typename T>
struct f<std::vector<T> > {
    void operator()()
    {
        std::cout << "vector" << std::endl;
    }
};

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

    return 0;
}

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

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