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