2009-08-18 16 views
11

我有一個模板函數:參考功能模板專門爲指針

template<typename T> 
void foo(const T& value) { bar(value); x = -1; } 

我想專門爲它一組類型:

template<> 
void foo<char>(const char& value) { bar(value); x = 0; } 
template<> 
void foo<unsigned char>(const unsigned char& value) { bar(value); x = 1; } 

它工作正常。當我編譯如下:

template<> 
void foo<char*>(const char*& value) { bar(value); x = 2; } 

我得到一個錯誤:

error C2912: explicit specialization; 'void foo(const char *&)' is not a specialization of a function template 

是否有可能專門與char*指針類型的參數,而不typedef'ing呢?

回答

20

當然。試試這個:

template<> 
void foo<char*>(char* const& value) {...} 

這是因爲const char*意味着指針const char,不是const指針char

+0

你也可以這樣做,對吧? '模板<> 無效美孚(爲const char * const的&值){...}' 這種做法對我的作品,但我不認爲需要指定'<爲const char *>' 'foo'之後。 – Alan 2017-03-02 22:00:11