Last active
November 6, 2018 15:33
-
-
Save jflopezfernandez/0137b61d9fe8c586a9acaf117b4a0abb to your computer and use it in GitHub Desktop.
Named Value Implementation in C++ Using Templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -------------------------------------------------------------------------------------------------------------------- | |
// | |
// Author: Jose Fernando Lopez | |
// Date: 6-November-2018 | |
// | |
// Description: This is a sample of how a named value might be implemented using a templated class in C++. | |
// I will update the constructor with proper move-semantics, add a copy constructor, etc., as | |
// well as add in string_view usage. I also need to add in operators in order for the value | |
// to be actually used. | |
// | |
// Sample Usage: | |
// | |
// int main() | |
// { | |
// NamedValue<int> age{ "Age", 25 }; | |
// | |
// std::cout << age; | |
// } | |
// | |
// Output: | |
// Age: 25 | |
// | |
// -------------------------------------------------------------------------------------------------------------------- | |
#ifndef PROJECT_NAME_NAMED_TYPE_H_INCLUDED | |
#define PROJECT_NAME_NAMED_TYPE_H_INCLUDED | |
#include <iostream> | |
#include <string> | |
template <typename T> | |
class NamedValue | |
{ | |
std::string Name; | |
T value; | |
public: | |
NamedValue() = delete; | |
NamedValue(char const *, char const *) -> NamedValue<std::string>; | |
NamedValue(std::string name, T val) | |
: name{ name }, value{ val } | |
{ } | |
auto Name() const noexcept { return name; } | |
auto Value() const noexcept { return value; } | |
template <typename U> | |
friend std::ostream& | |
operator << (std::ostream& outputStream, const NamedValue<U>& namedValue) | |
{ | |
return outputStream << namedValue.Name() << ": " << namedValue.Value() << '\n'; | |
} | |
}; | |
#endif // PROJECT_NAME_NAMED_TYPE_H_INCLUDED |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment