2014-04-02 229 views
1

是否可以專門爲模板類型設置模板功能?我不知道如果我的術語是正確的,所以我將提供一個簡單的示例與我想實現:如何使用模板類型專門化模板功能

#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: '無效F(無效)':

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

如何可以我實現這個行爲:函數模板已經在該功能定義

?擁有type f(void)簽名非常重要。這段代碼是否屬於函數的部分特化(在C++中被禁止)?

回答

10

您不能部分專門化模板功能,但您可以爲模板類。 所以你可以將你的實現轉發給一個專門的課程。 以下可能會有所幫助:(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(); 
} 
+0

能否請您解釋一下我爲什麼這是在部分功能專業化下降?謝謝! – Felics

+0

@Felics這是不可能的:見http://www.gotw.ca/publications/mill17.htm – jsantander

+1

如果'f_caller'是一個簡單的__functor__,這樣會更好。仍然 - +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; 
} 
+0

感謝您的努力,+1 :)我將使用細節/私有實現,因爲代碼更清晰:) – Felics