簡體   English   中英

如何使用模板類型專門化模板功能

[英]How to specialize template function with template types

是否可以為模板類型專門化模板函數? 我不知道我的術語是否正確,所以我將提供一個簡單的樣本,我想要實現的目標:

#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 ++中是禁止的)?

您不能部分專門化模板功能,但您可以使用模板類。 因此,您可以將實現轉發到專用類。 以下可能有所幫助:( 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();
}

嘗試盡可能接近原始代碼:

#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