0
我有下面的示例代碼,想了解爲什麼我無法在Linux上使用clang和g ++編譯它嗎?C++模板函數的解析
#include <iostream>
using namespace std;
typedef enum COLORS {
RED = 0,
GREEN,
BLUE,
ORANGE,
MAROON,
WHITE,
BLACK
} COLORS;
template <COLORS C> void whatColor(COLORS x) {
cout << "this can be any color!!!" << endl;
}
template<> void whatColor<RED>(COLORS x) {
cout << "this is RED!!!" << endl;
}
template<> void whatColor<GREEN>(COLORS x) {
cout << "this is GREEN!!!" << endl;
}
template<> void whatColor<BLUE>(COLORS x) {
cout << "this is BLUE!!!" << endl;
}
template<> void whatColor<ORANGE>(COLORS x) {
cout << "this is ORANGE!!!" << endl;
}
int main() {
const COLORS red=RED;
whatColor(red);
whatColor<RED>(RED);
whatColor<red>(red);
whatColor<RED>(red);
}
失敗,我看到的是這樣的:
CXX [misc] tmpl.cpp
src/tmpl.cpp:40:2: error: no matching function for call to 'whatColor'
whatColor(red);
^~~~~~~~~
src/tmpl.cpp:15:26: note: candidate template ignored: couldn't infer template argument 'C'
template <COLORS C> void whatColor(COLORS x) {
^
1 error generated.
make: *** [obj/tmpl.o] Error 1
爲什麼不能在這種情況下
@ROX嗨, 我已經刪除了輸入參數的功能,如果模板參數是一個顏色常量,工作正常。但是,我也需要它能夠使用COLORS變量: 'COLORS red = RED; whatColor();' 如果我把紅色作爲const,編譯器似乎足夠聰明,可以推斷出類型並且工作。但是,如果它不是const,它甚至不會編譯。發生此錯誤: src/tmpl。cpp:41:2:錯誤:沒有匹配函數調用'whatColor' whatColor (); src/tmpl.cpp:15:26:note:候選模板被忽略:無效顯式指定... –
TheBadCat
C++模板需要在編譯時修復的類型或值。如果您想使用運行時變量,那麼您不能將其用作模板參數。 (如果你真的想用模板來處理每種顏色,你可以在上面的switch語句示例中做到這一點)。我認爲你現在的錯誤信息是因爲它試圖通過固定爲顏色的類型來匹配模板參數,而不是通過不固定的值。 – ROX