Using std::hash<uint64_t> for custom class - c++

Do the following two return statements return the same thing?
class NonTrivialClass
{
public:
size_t hash() const
{
// variation 1
return std::hash<uint64_t>::_Do_hash(my_val_);
// variation 2, wanted to avoid creating the named object
std::hash<uint64_t> hasher;
return hasher(my_val_);
}
private:
// relevant info for hashing purposes is stored here
uint64_t my_val_;
}
I intuitively wanted to write something like
return std::hash<uint_64>(my_val_);
which did not compile (because I didn't init an instance of the struct?!). Is there a another way I am missing? Is worrying about creating the named hasher struct unneccessary?

A simpler way of writing it is using a temporary object:
return std::hash<uint64_t>{}(my_val_);
It does the same thing as your second approach.
I can't tell for sure what _Do_hash does, but in any case it is non-standard and should not be used, to avoid portability issues.
Since a google search didn't turn up any documentation of the function, I would assume that it is an implementation detail of the standard library implementation that you are using and that isn't meant to be used by user code. Therefore you shouldn't use it at all, even if you don't care about portability.
Also note that it doesn't matter for performance whether you use your approach with a named variable or my approach using a temporary. The compiler will almost surely generate identical code from it. Which you use is purely a matter of code style.

Related

How to share global constants with minimum overhead at runtime?

I am using C++11. I am not allowed to use external libraries like boost etc. I must use STL only.
I have a number of events, which must be identified as string constants. I am not allowed to use enums or ints or any other data type. For example:
"event_name1"
"event_name2"
"some_other_event_name3"
"a_different_event_name12"
Then I have some classes which need to use these strings, but don't know the other classes exist (they don't have anything to do with each other).
class Panel{
void postEvent(){
SomeSingleton::postEvent("event_name");
}
}
Another class::
class SomeClass{
SomeClass(){
SomeSingleton::listenForEvent("event_name");
}
void receiveEvent(){
//This function is triggered when "event_name" occurs.
//Do stuff
}
}
All these events are constants, and are used to identify things that are happening.
Here is what I have tried:
How to store string constants that will be accessed by a number of different classes?
Some of the persons there suggested I provide specific details of how to solve a concrete problem, so I have created this new question.
How can I store the strings in a common file, so that all the other classes that use these strings can refer to the same file?
I do not want to waste memory or leak memory during my app's lifetime (it is a mobile app)
compilation times are not a big deal to me, since the project isn't so big
there are expected to be maybe 50 different events.
It seems it would be more maintainable to keep all the strings in one file, and edit only this file as and when things change.
Any class can listen for any event, at any time, and I won't know prior to compilation
The easiest way would be to use a char const* constant, as it's way more optimizable and don't use dynamic allocations.
Also you can use std::string_view in the postEvent function, avoiding dynamic allocations. This step is optional. If you cannot have string views and still want to avoid dynamic allocations, then refer to your implementation's SSO max capacity and keep event names below that size.
Also consider that nonstd::string_view can be shipped as a C++11 library and most likely the abstraction you need. Library such as cpp17_headers and string-view-lite exist solely for that purpose.
It look like this:
constexpr auto event_name1 = "event_name1";
In a class as a static member it works the same way:
struct Type {
static constexpr auto event_name1 = "event_name1";
};
This will at most take space in the read-only static data of your executable.
In light of the fact that you're stuck with C++11, I think my suggestion from here still stands:
#ifndef INCLUDED_EVENT_NAMES
#define INCLUDED_EVENT_NAMES
#pragma once
namespace event_names
{
constexpr auto& event_1 = "event_1";
constexpr auto& event_2 = "event_2";
}
#endif
Defining named references to string literal objects is very simple, does not require any additional libraries, is guaranteed to not introduce any unnecessary objects, won't require any additional memory over the storage for the statically-allocated string literal objects that you'd need anyways, and will not have any runtime overhead.
If you could use C++17, I'd suggest to go with the std::string_view approach, but in C++11, I think the above is most-likely a good compromise for your application.
Global const std::string has one drawback it need processing during startup and creates copy of string literal.
The linked SO answear uses constexpr std::string_view and this is cool solution since constructor is constexpr so nothing have to be done on startup. Also it doesn't create any copy. Problem is that this is C++17
Use of const char [] (or auto or constexpr) is old proven solution. You can compare std::string with it without any extra overhead.
You can create header file for all that strings and let linker to remove all duplicates. It was working like that in old C++.
You can have a struct of static strings:
struct MyNames
{
static const std::string name1;
};
And in a cpp:
const std::string MyNames::name1 = "foo";
You can then access the names from all your required locations. In C++17, you would have used string_view instead to avoid object construction. But this seems to be a duplicate of this answer, basically: https://stackoverflow.com/a/55493109/2266772
For the sake of proper abstraction and good design, you should define an event class. This event class will have either:
A method which provide a string (e.g. name() or system_name())
A conversion operator to a string (not recommended)
A to_string() freestanding function which takes such an event (not recommend)
But beyond that - all of your class can now use an enum, or an index, or whatever they like - they'll just need to use the conversion method whenever they interact with whatever it is that requires strings. Thus none of your classes has to actually know about those strings itself.
The strings themselves can stay within the .cpp implementation file of the class, and nobody else has to know about them. (unles they are actually defined in code that's not yours, but that's not how you described the problem.)

Enforce type safety in C++ without using extra classes

I am somewhat familiar with type safety, and have used it successfully before in methods which receive several parameters of the same type (bool) to avoid confusion. For example:
// Old version of the method
void sendPackage(bool sendImmediately, bool dividePacket);
// Type safe version
enum SendImmediatelyPreference
{
SEND_IMMEDIATELY,
DO_NOT_SEND_IMMEDIATELY
};
enum PacketDivisionPreference
{
DIVIDE_PACKET,
DO_NOT_DIVIDE_PACKET
};
void sendPackage(
SendImmediateltPreference immediatePref,
PacketDivisionPreference divisionPref);
So the cryptic sendPackage(true, false) becomes sendPackage(SEND_IMMEDIATELY, DO_NOT_DIVIDE_PACKET).
The problem is that this is only an option for bool. I have a method that accepts several std::vector<std::string> and I'd like to minimise the posibility of the user inputting the arguments in the wrong order.
I can think of creating different classes which contains an std::vector<std::string> and either override tons of the std::vector methods or expose the internal vector.
Is there an easier way, some sort of typedef which enforces type safety? Using boost would be okay.
How about an alternative approach using named parameters? There are several ways of going about this in C++ described here. The tag approach using a tuple looks reasonable. There is also boost parameter.
This doesn't offer strong type safety, but you could argue that the user is just as likely to call the wrong constructor to make their type safe object as they are to use the wrong tag when calling your function. This situation is less likely to occur if the types are used throughout your application vs defined only for one particular function.
See also the discussion of boost strong typedef vs parameter for a similar purpose here.
Not sure I understood you correctly, but maybe this can help:
enum SendImmediatelyPreference : bool // allows only 2 options:
{
DO_NOT_SEND_IMMEDIATELY, // false
SEND_IMMEDIATELY // true
}
What about creating a class that inherits (public) from std::vector to have a strong typecheck. The advantage is that you only need to rewrite constructors..
You can also regroup your parameters in a std::unordered_map>, to implement argument as a dict (like in python, or javascript)
BOOST_STRONG_TYPEDEF is precisely a typedef which enforces type safety.
However, this answer provides some caveats related to using this strong typedef for just a function, and argues that the types should be used all over the code to prevent unnecessary castings.
I like to bundle the parameters in a config class or struct. For example:
struct SendOptions
{
bool send_immediately = false;
bool divide_packet = false;
// ...
};
void sendPackage(SendOptions options);
This has the additional advantage the extra options can be added later without needing to change the interface of sendPackage(SendOptions).
This does not increase type safety but it does help to prevent errors (especially if there are a lot of parameters), which is probably the goal you're trying to achieve.

share code between very similar methods

My job is to fully rewrite an old library for GIS vector data processing. The main class encapsulates a collection of building outlines, and offers different methods for checking data consistency. Those checking functions have an optional parameter that allows to perform some process.
For instance:
std::vector<Point> checkIntersections(int process_mode = 0);
This method tests if some building outlines are intersecting, and return the intersection points. But if you pass a non null argument, the method will modify the outlines to remove the intersection.
I think it's pretty bad (at call site, a reader not familiar with the code base will assume that a method called checkSomething only performs a check and doesn't modifiy data) and I want to change this. I also want to avoid code duplication as check and process methods are mostly similar.
So I was thinking to something like this:
// a private worker
std::vector<Point> workerIntersections(int process_mode = 0)
{
// it's the equivalent of the current checkIntersections, it may perform
// a process depending on process_mode
}
// public interfaces for check and process
std::vector<Point> checkIntersections() /* const */
{
workerIntersections(0);
}
std::vector<Point> processIntersections(int process_mode /*I have different process modes*/)
{
workerIntersections(process_mode);
}
But that forces me to break const correctness as workerIntersections is a non-const method.
How can I separate check and process, avoiding code duplication and keeping const-correctness?
Like you've noted, your suggestion will break const-correctness.
This is because your suggestion essentially includes wrapping the existing code with a new interface but not the redesign of internals. This approach has severe limitations as it's directly affected by the underlying blocks.
Instead I would suggest you to redesign the existing code and just break the checkIntersections in 2 public methods that you need. The checkIntersections will include the checking part and processIntersections will include the call to checkIntersections and the processing code based on the result of checkIntersections.
In this particular case, breaking const-correctness shouldn't matter. You (as the author of workerIntersections() know that it will only perform non-const operations if invoked from processIntersections(), a non-const function. Therefore, it's safe to implement checkIntersections() like this:
std::vector<Point> checkIntersections() const
{
const_cast<TypeOfThis*>(this)->workerIntersections(0);
}
Of course, you must make sure that workerIntersections() really only does const operations when invoked with 0.
const_cast exists in the language for a reason, mainly interoperability with legacy code which ignores const correctness. That's exactly what you're doing, so as long as you do it safely, you're fine using const_cast.

Using dynamic typing in D, a statically typed language

I was implementing a dynamic typing library for D when I ran across an interesting problem.
Right now, I've succeeded in making a function called dynamic() which returns a dynamic version of an object.
For example:
import std.stdio, std.dynamic.core;
class Foo
{
string bar(string a) { return a ~ "OMG"; }
int opUnary(string s)() if (s == "-") { return 0; }
}
void main(string[] argv)
{
Dynamic d = dynamic(new Foo());
Dynamic result = d.bar("hi");
writeln(result); // Uh-oh
}
The problem I've run across is the fact that writeln tries to use compile-time reflection to figure out how to treat result.
What's the first thing it tries? isInputRange!(typeof(result))
The trouble is, it returns true! Why? Because I have to assume that all members which it needs exist, unless I can prove otherwise at run time -- which is too late. So the program tries to call front, popFront, and empty on result, crashing my program.
I can't think of a way to fix this. Does anyone have an idea?
You are trying to make two fundamentally different concepts work together, namely templates and dynamic typing. Templates rely very much on static typing, isInputRange works by checking which attributes or methods a type has. Your dynamic type is treated as having every attribute or method at compile time, ergo it is treated as fulfilling every static duck-typing interface.
Therefore, to make Dynamic work in a statically typed environment, you have to provide more static information at some places.
Some solutions I can see:
provide your own dynamically typed implementations for heavily used functions. The whole problem you are having is caused by the fact that you are trying to use generic functions that assume static typing with dynamic types.
explicitly make dynamic a range of char, and care for the conversion to string of the underlying data yourself. (You'd have to have a custom toString method anyways if the isInputRange issue would not exist, because otherwise its result would again be of Dynamic type). This would probably make writeln(d); work.
provide wrappers for dynamic that allow you to pass dynamic types into various templated functions. (Those would just exhibit a static interface and forward all calls to Dynamic).
Eg:
Dynamic d;
// wrap d to turn it into a compile-time input range (but NOT eg a forward range)
Dynamic d2=dynamic(map!q{a*2}(dynInputRange(d)));
// profit
4 . Add a member template to Dynamic, which allows to statically disable some member function names.
Eg:
static assert(!isForwardRange!(typeof(d.without!"save")));
what is wrong with using std.variant which implements all you need for dynamic typing (along with quite a bit of syntactic sugar)
Could you provide an overload for isInputRange? Something like this (note that I haven't looked at the implementation of isInputRange):
template isInputRange(T : Dynamic) {
enum isInputRange = false;
}
If this is provided by your dynamic.core, I think this overload should be chosen before the std lib one.
For the general case Dynamic has to accept any method lookup at compile time, as you said. Suppose for a moment that you could prevent the isInputRange predicate to evaluate to true, now the wrong code will be generated when you try to create a Dynamic from an input range.
I don't think this is fixable, at least not in a general way. In this particular case the best solution I can think of is that Dynamic provides it's own version of toString, and writeln would prefer that over the inputRange specialization. I believe writeln doesn't do this at the moment, at least not for structs, but it probably should.
Another compromise would be to disallow a few methods such as popFront in the opDispatch constraint, instead Dynamic would provide opIndex or a member object to access these special cases. This might not be as bad as it sounds, because the special cases are rare and using them would result in an obvious compiler error.
I think that the best way to salvage this kind of method resolution for Dynamic is to fix writeln and accept that Dynamic will not work with all templated code.
Have you looked into std.variant?
import std.stdio, std.variant;
class Foo {
string Bar(string a) {
return a ~ " are Cool!";
}
}
void main() {
Variant foo = new Foo();
Variant result = foo.peek!Foo.Bar("Variants");
writeln(result); // Variants are Cool!
}
http://www.d-programming-language.org/phobos/std_variant.html

Protecting class from getting instantiated before main()

I want to ensure that my C++ class is never instantiated before main() is entered. Is there any way to achieve this?
--
Some clarification:
I am writing an embedded application. My class must be static (reside in the BSS), but at instantiation it requires some resources that aren't available before certain things has been initialized in start of main(). So I want to make it a Meyers singleton. Ideally I would like to make some kind of assert that ensures that MyClass::instance() is never called before main().
Restricting construction of a class before some method gets called is going to be a losing battle. Especially if that method is main(). Can I ask why you have this requirement? Perhaps there is another way to tackle the actual problem you're attempting to solve.
Edit: thanks for the CTQ, and judging from it your best bet is probably the simplest solution, which is a static boolean. Since it's embedded I'm going to make the assumption that you pretty much control the entire environment. A simple assert in your ::instance() based on a static bool is probably all that you need.
Taking it one step further, It sounds like you need dependency injection or some other way of assuring that your resources are initialized in the correct order, which I'll be honest, is not a problem I've tackled in C++ (let alone on an embedded system). I can't give any additional insight into the most effective means for that case and would suggest you consider maybe one of the other answers to this question.
One thing you can do is have a static method like MyClass::enableConstruction() which turns on a static flag in the class. If the c'tor is called when this flag is false then it throws an exception. This way you'll alteast have some run-time indication that someone is breaking the rules.
Notice that you should be careful with the initialization of that static flag. To avoid any construction order problems it would probably be best to make it a singleton that is initialized when first accessed.
Give your class a static bool that is set on the first instantiation, and check it at the beginning of main()
Using a factory or making the constructor private will not stop it being instantiated in the constructor of a class that is instantiated before main()
There is no clean way to do this. Perhaps there's something hackish you can do to achieve this end, but you shouldn't.
Describe the fuller need and I'm certain a better solution can be found.
If you can control the code that gets executed when main() starts, then you can have a function like this:
bool wasMain (bool inMain = false) {
static bool passedMain = false;
return passedMain |= inMain;
}
Then, first line within main use wasMain(true) and it shall return true from there onwards, whereas it will return false until that point.
Edit: I just love shorter code, the above implementation can be simplified to:
bool wasMain (bool inMain = false) {
static bool passedMain = false;
if (inMain)
passedMain = true;
return passedMain;
}
One possible way is to instance the class inside main. i.e.
MyClass * g_thing = 0;
int main()
{
g_thing = new MyClass();
}
Other than that it's a tricky, compiler specific mess. What are you trying to achieve?