【问题标题】:How to specialize template function with template types如何使用模板类型专门化模板功能
【发布时间】:2014-05-13 16:01:42
【问题描述】:

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

#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给我

错误 C2995: 'void f(void)' : 函数模板已定义

关于这个功能:

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

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

【问题讨论】:

    标签: c++ templates partial-specialization


    【解决方案1】:

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

    【讨论】:

    • 你能解释一下为什么这属于偏函数专业化吗?谢谢!
    • 如果f_caller 是一个简单的函子,那就更好了。仍然 - +1。
    【解决方案2】:

    尽量接近原代码的是:

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

    【讨论】:

    • 感谢您的努力,+1:) 我将使用详细信息/私有实现,因为那里的代码更清晰:)
    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多