Ich habe den folgenden Beispielcode und möchte Hilfe bekommen, um zu verstehen, warum ich nicht in der Lage bin, es unter Verwendung von CLANG und G ++ unter Linux zu kompilieren?C++ - Vorlage Funktion Auflösung
#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);
}
Das Scheitern ich sehen will, ist dies:
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
Es ist mir unklar, warum es nicht das Argument ist in diesem Fall
Hallo @ROX, Ich habe den Eingangsparameter an die Funktion entfernt und das funktioniert gut, wenn die Template-Parameter eine FARBEN konstant ist. Ich brauche aber auch eine COLORS-Variable: 'FARBEN rot = ROT; whatColor(); ' Wenn ich rot ein const mache, scheint der Compiler schlau genug, um den Typ abzuleiten und es funktioniert. Wenn es jedoch kein Const ist, wird es nicht einmal kompiliert. Geben Sie diesen Fehler ein: src/tmpl.cpp: 41: 2: error: keine passende Funktion für den Aufruf von 'whatColor' whatColor (); src/tmpl.cpp: 15: 26: Hinweis: Kandidatenvorlage ignoriert: ungültig explizit angegeben ... –
TheBadCat
C++ - Vorlagen erfordern Typen oder Werte, die zur Kompilierzeit festgelegt werden. Wenn Sie eine Laufzeitvariable verwenden möchten, können Sie sie nicht als Vorlageparameter verwenden. (Wenn Sie wirklich Templates verwenden möchten, um jede Farbe zu behandeln, können Sie das im obigen Beispiel der switch-Anweisung tun). Ich denke, Ihre Fehlermeldung ist jetzt, weil es versucht, die Vorlage Parameter nach Typ, der als Farben festgelegt ist, nicht nach Wert, der nicht behoben ist. – ROX