2016-11-08 46 views
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 

为什么不能在这种情况下

回答

0

与代码推断参数类型目前尚不清楚对我说:

template <COLORS C> void whatColor(COLORS x){...} 

您定义了一个模板函数,以Color类型的值C为模板,此函数巧合地发生在ta柯一个颜色X作为参数(这是不实际使用)

还专门随后该功能C.

的一些可能的值,当你调用

whatColor(red); 

您提供值为Color x,但不是C值。由于X和C不相关(即使它们都是颜色),编译器无法决定使用哪个C值。

,你应该决定是否要颜色要动态或静态类型(是固定在编译时或没有),此刻你的代码试图既

例如混合它目前将有可能这样称呼它

whatColor<RED>(BLUE); 

这真的有点奇怪。 C = RED,X = BLUE(但X被忽略),如果你要修复在编译时的颜色,你可以删除X功能参数,只需要使用C++模板参数

template <COLORS C> void whatColor() //definition 
whatColor<RED>(); // call 

,或者如果

要使用X参数的功能,那么就不要使用模板

void whatColor(COLORS X) 
{ 
    // maybe use a switch statement on X 
} 

如果不同的颜色是不同的类型,而不是再重载或模板代码将工作(不,我建议无论是对值这个)

class Red{}; 
class Blue{}; 
template <typename COLORSTYPE> void whatColor(COLORSTYPE x) 
{ 
    // ... 
} 

//或重载

void whatColor(Red dummy){//...} 
void whatColor(Blue dummy){//...} 

Red red; 
whatColor(red); 
+0

@ROX嗨, 我已经删除了输入参数的功能,如果模板参数是一个颜色常量,工作正常。但是,我也需要它能够使用COLORS变量: 'COLORS red = RED; whatColor ();' 如果我把红色作为const,编译器似乎足够聪明,可以推断出类型并且工作。但是,如果它不是const,它甚至不会编译。发生此错误: src/tmpl。cpp:41:2:错误:没有匹配函数调用'whatColor' whatColor (); src/tmpl.cpp:15:26:note:候选模板被忽略:无效显式指定... – TheBadCat

+0

C++模板需要在编译时修复的类型或值。如果您想使用运行时变量,那么您不能将其用作模板参数。 (如果你真的想用模板来处理每种颜色,你可以在上面的switch语句示例中做到这一点)。我认为你现在的错误信息是因为它试图通过固定为颜色的类型来匹配模板参数,而不是通过不固定的值。 – ROX