Ich habe dieses Beispiel/Klasse in einem Buch zum Erstellen von SDBM-Hashes zur Kompilierzeit gefunden. Leider kompiliert es nicht (weder mit C++ 11 noch mit C++ 14). Ich bekomme error: call to non-constexpr function
. Ich habe es ein bisschen probiert, aber ich kann es nicht funktionieren lassen. Also hier ist meine Frage:Kompilierzeit Hash mit consExpr
- Warum funktioniert es nicht und wie könnte es behoben werden? (Es tut mir leid, ich weiß, es ist eine allgemeine Frage, aber zumindest für einen ganz bestimmten Fall)
Full (nicht in Betrieb) Beispiel für Sie zu testen:
#include <iostream>
template <int stringLength>
struct SDBMCalculator
{
static inline int Calculate(const char* const stringToHash, int& value)
{
int character = SDBMCalculator<stringLength - 1>::Calculate(stringToHash, value);
value = character + (value << 6) + (value << 16) - value;
std::cout << static_cast<char>(character) << std::endl << value << std::endl << std::endl;
return stringToHash[stringLength - 1];
}
static inline int CalculateValue(const char* const stringToHash)
{
int value = 0;
int character = SDBMCalculator<stringLength>::Calculate(stringToHash, value);
value = character + (value << 6) + (value << 16) - value;
std::cout << static_cast<char>(character) << std::endl << value << std::endl << std::endl;
return value;
}
};
template <>
struct SDBMCalculator<1>
{
static inline int Calculate(const char* const stringToHash, int& value)
{
return stringToHash[0];
}
};
int main()
{
constexpr int eventID = SDBMCalculator<5>::CalculateValue("Hello");
std::cout << eventID << std::endl;
}
viel im Voraus Dank für deine Zeit und Mühe!
Das einzige, was ich sagen kann, kommt die Fehlermeldung wiederholen: Sie rufen eine Funktion, die nicht als constexpr markiert. Ihre 'Calculate' und' CalculateValue' Funktionen sind nicht constexpr. Sie können bei der Auswertung eines constexpr-Wertes keine non-constexpr-Funktionen aufrufen. – CygnusX1
Sie wollen wahrscheinlich 'const' dort. Der Wert der Funktion ist während der Kompilierzeit nicht bekannt, da Sie während der Laufzeit ein Argument angeben. – Ron