Gamedev Framework (gf)  0.10.0
A C++14 framework for 2D games
String identifiers

Table of Contents

Introduction

A gf::Id represents an identifier that has been computed from a string. Technically, it's a message digest from the Fowler–Noll–Vo 1a hash function.

How to get an id from a string?

There are two ways to get an id from a string. The first one is to call gf::hash with the string. You can use a C string or a std::string or anything that can be converted to a gf::StringRef.

gf::Id id1 = gf::hash("C string");
std::string str("std::string");
gf::Id id2 = gf::hash(str);

The second one is to use the user-defined literal _id. First, you have to include a using namespace directive in order to be able to use this user-defined literal.

using namespace gf::literals; // necessary to use _id

Then, you can use the user-defined literal on literal strings.

gf::Id id1 = "C string"_id;
gf::Id id2 = "std::string"_id;

The main advantage is that the id is computed at compile-time.

static_assert("foobar"_id == 0x85944171f73967e8, "It works at compile-time!");

So, you can even use this property to compute a switch statement on a string.

std::string input = myInput();
switch (gf::hash(input)) {
case "Foo"_id:
// input is "Foo"
break;
case "Bar"_id:
// input is "Bar"
break;
case "Baz"_id:
// input is "Baz"
break;
}