I am learning cpp. I thought that memeber type are functions/variable which belong to a type.
For exanple in the following
class person
{
public:
string name;
int age;
};
name and age are member type (in this case member class) of the person class.
Recently I started to read about <chrono> library, and thaen I started to confused.
There is for example class system_clock which has time_point member type. But on the other hand there is also class time_point which has Clock member type (e.g class system_clock).
How can a class contains sompe type as a member type and also be a member type of its own member type.
I hope that I succeeded to explain my confusion.
You are confusing non-static data members with nested member type aliases.
Examples of non-static data member are name and age in:
class person
{
public:
string name;
int age;
};
name and age store values inside a specific instance of person. They have an address in an lvalue instance of person so you can find out what that address is:
person p;
string* np = &p.name; // this is where p.name lives in memory
A nested type alias does not occupy storage. For example:
class person
{
public:
using name_type = string;
string name;
int age;
};
person::name_type is a type alias for string. It doesn't occupy storage. You could use it to create a string:
person::name_type x = string{};
system_clock::time_point is a type alias for:
time_point<system_clock, system_clock::duration>
time_point::clock is a type alias for Clock in:
time_point<Clock, ...>
So, time_point<system_clock, system_clock::duration>::clock is the same type as system_clock.
system_clock does not store a time_pont. Indeed, it does not store anything at all (no non-static data members).
time_point does not have a clock as a non-static data member. time_point only stores a duration which has the type of time_point's second template parameter in:
template <class Clock, class Duration = typename Clock::duration>
class time_point;
These type aliases might be used like this:
system_clock::time_point tp = system_clock::now();
Though the use of auto here is much easier (and my preference):
auto tp = system_clock::now();
Use of time_point::clock might come in handy if you had a generic time_point and you needed to call now() for whatever clock that time_point is measured with:
template <class TimePoint>
void some_function(TimePoint tp)
{
using Clock = typename TimePoint::clock;
auto now = Clock::now();
...
This latter use-case is more rare, but the capability is there if you need it.
In general, when learning about <chrono>, most people do better by reading tutorial-like information about it, or looking at example code, or reading other's Stack Overflow questions about it. When people try to learn about <chrono> by studying its implementation, they invariably have a strong negative reaction to its relatively complex implementation.
Its implementation is relatively complex because it is far more powerful than alternatives such as timespec. However its common everyday use has very simple and safe syntax. For common use cases you don't even need to know that everything is templated. You can just use things like system_clock::now(), nanoseconds and hours.
I recommend reading some of the [chrono]-tagged questions. I also recommend reading parts of the <chrono> proposal found here:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm
The committee itself needed a tutorial on this subject, and this paper contains a pretty good one. Skip the parts containing proposed wording unless you're in need of a sleeping aid. The paper is somewhat dated in that a few details have changed, but not many. One example is that monotonic_clock has since been renamed to steady_clock. Another detail is that constexpr has since been generously applied. And user-defined literals have since been added to the 6 concrete duration types.
Finally, Nicolai M. Josuttis' second edition of The C++ Standard Library - A Tutorial and Reference has a nice section on <chrono>.
Related
I've read many text mentioned the in-class-initializer and I've searched many question on stackoverflow, However I didn't found any precise explanation on what is the in-class-initializer. And as far as I understood the variable of build-in type declared outside any function will be default initialized by the compiler, does the in-class-initilizer doing the same action for a declared variable?
Here is a simple example for in-class initialization. It's useful for less typing, especially when more than one constructor signatures are available. It's recommend in the core guidelines, too.
class Foo {
public:
Foo() = default; // No need to initialize data members in the initializer list.
Foo(bool) { /* Do stuff here. */ } // Again, data member already have values.
private:
int bar = 42;
// ^^^^ in-class initialization
int baz{};
// ^^ same, but requests zero initialization
};
As the data members are explicitly initialized, the second part of your questions doesn't really apply to to in-class initialization.
I am implementing a command pattern implementations with large number of actions and parameters involved. To simplify I am planning to use class that can hold all possible params to module in a map.
class ParamBag {
public:
add(int paramId, shared_ptr<IParam> param);
bool contains(int paramId);
std::shared_ptr<IParam> get(paramId);
private:
int mask;
std::map<int, std::shared_ptr<IParam>> params;
};
One clear downside of this implementation is each param has to extend from IParam interface, can I somehow simplify this.
If the one that uses the param after the get knows the type of the param, then you can use c++17 std::any, or if you must use c++11 you can try boost::any, or if none of those you can resort back to a void*.
The difference is that void* will not fail on a cast to a wrong type, where any_cast would throw an exception, or return nullptr if used with a pointer. You would also need to use a custom deleter in the std::shared_ptr in order to be able to free the void*.
I frequently come across a situation where we create a class that acts on some enumeration, but later we derive and we want to add more values to the enumeration without changing the base class.
I see this question from 2009:
Base enum class inheritance
However, I know there were a number of changes to enum in C++11, 14, 17.
Do any of those changes allow for extension of enums from base class to derived?
class Base
{
enum State {STATE_1, STATE_2, STATE_3};
};
class Derived : public Base
{
enum State {STATE_4};
};
...where we want derived to have an enumeration describing the states it can be in, which are: STATE_1, STATE_2, STATE_3, and STATE_4. We don't really want to change the enumeration in the base class, because other derived classes might not have the ability to be in STATE_4. We don't really want to create a new enumeration either, because we already have one for State in the Base.
Do we still use static const values instead in order to accomplish this 8 years later?
class Base
{
static int STATE_1= 0;
static int STATE_2= 1;
static int STATE_3= 2;
};
class Derived : public Base
{
static int STATE_4= 3;
};
No, C++ does not allow this sort of thing. Base::Color is a completely separate type from Derived::Color, with zero connection to them. This is no different from any other nested types; nested types defined in a base class are not connected to nested types defined in a derived class.
Nor can enumerations be inherited from one another.
This sort of things tends to go against good OOP practices anyway. After all, if a derived class introduces a new enumerator, how would the base class handle it? How would different derived class instances handle it?
If Base defines an operation over an enumeration, then Base defines the totality of the enumeration it operates on, and every class derived from it ought to be able to handle all of those options. Otherwise, something is very wrong with your virtual interface.
Why not just using namespaces to group enums?
namespace my_codes {
enum class color { red, green, blue } ;
enum class origin { server, client } ;
} // my_codes
Usage might be
struct my_signal {
my_codes::color flag ;
my_codes::origin source ;
} ;
But beware: "overkill is my biggest fear..." :) I would not enjoy some deep hierarchy of namespaces with enums in them and a such ...
We have people who run code for simulations, testing etc. on some supercomputers that we have. What would be nice is, if as part of a build process we can check that not only that the code compiles but that the ouput matches some pattern which will indicate we are getting meaningful results.
i.e. the researcher may know that the value of x must be within some bounds. If not, then a logical error has been made in the code (assuming it compiles and their is no compile time error).
Are there any pre-written packages for this kind of thing. The code is written in FORTRAN, C, C++ etc.
Any specific or general advice would be appreciated.
I expect most unit testing frameworks could do this; supply a toy test data set and see that the answer is sane in various different ways.
A good way to ensure that the resulting value of any computation (whether final or intermediate) meets certain constraints, is to use an object oriented programming language like C++, and define data-types that internally enforce the conditions that you are checking for. You can then use those data-types as the return value of any computation to ensure that said conditions are met for the value returned.
Let's look at a simple example. Assume that you have a member function inside of an Airplane class as a part of a flight control system that estimates the mass of the airplane instance as a function of the number passengers and the amount of fuel that plane has at that moment. One way to declare the Airplane class and an airplaneMass() member function is the following:
class Airplane {
public:
...
int airplaneMass() const; // note the plain int return type
...
private:
...
};
However, a better way to implement the above, would be to define a type AirplaneMass that can be used as the function's return type instead of int. AirplaneMass can internally ensure (in it's constructor and any overloaded operators) that the value it encapsulates meets certain constraints. An example implementation of the AirplaneMass datatype could be the following:
class AirplaneMass {
public:
// AirplaneMass constructor
AirplaneMass(int m) {
if (m < MIN || m > MAX) {
// throw exception or log constraint violation
}
// if the value of m meets the constraints,
// assign it to the internal value.
mass_ = m;
}
...
/* range checking should also be done in the implementation
of overloaded operators. For instance, you may want to
make sure that the resultant of the ++ operation for
any instance of AirplaneMass also lies within the
specified constraints. */
private:
int mass_;
};
Thereafter, you can redeclare class Airplane and its airplaneMass() member function as follows:
class Airplane {
public:
...
AirplaneMass airplaneMass() const;
// note the more specific AirplaneMass return type
...
private:
...
};
The above will ensure that the value returned by airplaneMass() is between MIN and MAX. Otherwise, an exception will be thrown, or the error condition will be logged.
I had to do that for conversions this month. I don't know if that might help you, but it appeared quite simple a solution to me.
First, I defined a tolerance level. (Java-ish example code...)
private static final double TOLERANCE = 0.000000000001D;
Then I defined a new "areEqual" method which checks if the difference between both values is lower than the tolerance level or not.
private static boolean areEqual(double a, double b) {
return (abs(a - b) < TOLERANCE);
}
If I get a false somewhere, it means the check has probably failed. I can adjust the tolerance to see if it's just a precision problem or really a bad result. Works quite well in my situation.
This question is out of pure curiosity. How does Cocoa define the id type? Is it just a typedef for a void *? Also, if you know which header file it is defined in, I would be interested in taking a look.
Hold down the command key and double click on any highlighted term to jump to its definition.
typedef struct objc_class *Class;
typedef struct objc_object {
Class isa;
} *id;
typedef struct objc_selector *SEL;
typedef id (*IMP)(id, SEL, ...);
It is delcared in /usr/include/objc/objc.h (on Leopard) as follows:
typedef struct objc_object {
Class isa;
} *id;
Which means it is not void * at all, but rather a pointer to a struct that contains a single member, pointing at the class definition. Interesting indeed.
I remember when I was just getting into C and learning that Objective-C was initially implemented as just a preprocessor layer on top of C. It isn't quite like that anymore.
The best reading on the topic I've found:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.html
in objc.h
typedef struct objc_class *Class;
typedef struct objc_object {
Class isa;
} *id;
To find out on your own, in XCode, right click id -- or any other type -- and select Jump to definition. It's interesting to note the similarities to other C/C++ based object systems; an object pointer -- an id -- points to a struct that starts with a point to shared class information. I many C++ implementations, that would be the virtual function table, as it would be with Microsoft's COM. In Cocoa, the particulars of objc_class aren't revealed to us in the header file.
The id type is generally declared like:
typedef struct objc_object *id;
This is critical for Objective-C++ where the type is part of a mangled function name.
You can take a look in /usr/include/objc/objc.h
You can refer the doc here : http://opensource.apple.com/source/objc4/objc4-437/runtime/objc.h
Hope this will do a favor for you