c++ - 如何使用模板类型专门化模板函数

标签 c++ templates partial-specialization

是否可以为模板类型特化一个模板函数?我不知道我的术语是否正确,所以我将提供一个简单的示例来说明我想要实现的目标:

#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;
}

此代码无法编译。 VS2013 给我

error C2995: 'void f(void)' : function template has already been defined

关于这个函数:

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

我怎样才能实现这种行为?拥有type f(void) 签名非常重要。此代码是否属于函数的部分特化(在 C++ 中禁止)?

最佳答案

你不能部分特化模板函数,但你可以部分特化模板类。 所以你可以将你的实现转发给一个专门的类。 以下内容可能有所帮助:( 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();
}

关于c++ - 如何使用模板类型专门化模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22810293/

相关文章:

c++ - 指针和非指针类型的重载 -> 运算符

c++ - 在未调用的转换函数上在模板中编译错误

c++ - 部分模板参数应用程序的部分模板特化不适用于 GCC 4.8.1

c++ - 如何将现有模板类部分特化为新类型?

c++ - Qt Controller 脚本在 ComponentSelectionPage 中选择组件

c++ - 导出 COM 注册信息

c++ - 函数中二维字符数组的长度

c++ - 为模板化类专门化模板函数

c++ - 多种类型的部分类模板特化

c++ - boost::lockfree::queue 在 c++11 中不是无锁的吗?