C++11: How to create an enum class inside an class that behaves like a sub class? - class

To explain my problem I posted an example below. The code in this form is not tested so there might be some syntax mistake in it. As I have to work with a lot of registers in an integrated circuit with their addresses which can be remapped, it would be very useful to create structures like that below. Is there some trick to create these structures? As this example does not work the way I want it because foo requires a Country object and Country::Europe::Italy is invalid as parameter.
// I want to create a structure like this
class myClass {
public:
class Country {
enum class Europe {
England,
France,
Germany,
Italy
};
enum class Asia {
China,
Japan
};
};
// Here I want to make sure, that the method is only
// called with a Country element and e.g. Italy should
// behave like a Country object. Actually it should behave
// as if it is derived from Country.
int foo(Country c);
};
int main() {
myClass myC();
// Exemplary call of the method foo
myC.foo(myClass::Country::Europe::Italy);
}

You cannot use enum class to achieve your goal. However, you can use a namespace with a set of hardcoded constexpr objects:
struct Country
{
int _id;
};
namespace Countries
{
namespace Europe
{
constexpr Country Italy{0};
constexpr Country France{1};
};
};
Usage:
myC.foo(Countries::Europe::Italy);

A proper example using registers and a better explanation would have been better. I guess you want to remap from one register name to another. A suggestion:
class Register {
public:
enum class UserName {
REG_IO0,
REG_MEM1
};
enum class CPUName {
REG_INT0,
REG_INT1
};
void setMapping(UserName from, CPUName to); // store the mapping
CPUName getMapping(UserName name) const; // retrieve the mapping
private:
std::map<UserName, CPUName> m_registerMap;
};
If you want you could implement get/set methods for the registers in that class if you store the indexes/adresses of the registers. Either use templates or overload them for different data types.

You can explicitly use an enum type as a function or constructor argument, restricting the caller to using that enumeration.
The thing you can't trivially do is combine multiple enum definitions in the way that you have suggested.
You could write several constructors, one for each of the enums Europe, Asia, etc, but that would be work, especially if you have a number of functions that need to take these enums as arguments.
--OR--
You could define one big enum, and define fixed value separators for each subgroup, so you can compare the enum value against these guard values to identify the subgroup. You lose the sub-grouping if you do that. You could use c++11 constant enum initialisers to construct enum value members in subclasses for each continent - but note these are only available for enum class from c++17 (so I am using a nested class trick to provide the member namespace enforcement - in c++17 you could have enum class Location - you can write this in c++11 but you can't then do the const initialisers). The values follow the above rule of separators, but callers have to indirect through the subclasses to get the names.
class Country
{
class Location {
enum Value {
None =0,
Europe = 0x0100,
Asia = 0x0200,
//etc
};
};
struct Asia {
const Location::Value Japan { Location::Asia + 1 };
//etc
};
struct Europe {
const Location::Value UnitedKingdom { Location::Europe + 1 };
//etc
};
// etc
};
Then you could have
class myClass {
public:
myClass(Country::Location::Value v);
};
And call it with
myClass instance(Country::Asia::Japan);
-- OR --
You could define another structure who's only purpose is to take the various enumerations and convert them to a pair of values for the continent and country index. You could then use that structure as your function parameter, and allow auto-conversion from that structure. This means you only do the conversion once, and callers to your code are not impacted. You could use the guard ranges such that you don't need to explicitly store the continent code, just the raw country number would be unique across all your enums.

Related

Why is it necessary to use constructors in dart programming language classes?

I'm a beginner learning dart from the book dart apprentice and I reached where they were discussing constructors in dart classes, the book was implying that constructors create instances of the class which I understood but I needed more info about constructors. So I googled and some results repeated what was already in the book about it being used to create instances of a class while others also showed that it's used to instantiate class properties, but my problem is with the other answer which I found that they are used to instantiate properties of a class, but my question is: I instantiate all class properties when I create the class by declaring the property variables, like this:
class UserClass{
userClassProperty = "";
anotherUserClassProperty = ""; }
why is the constructor also needed to instantiate class properties?
Often, values are unique to every class instance.
Consider the following example:
class Point {
final int x;
final int y;
const Point(this.x, this.y);
double get distanceToOrigin => sqrt(x * x + y * y);
}
If the x and y values were defined inside the class, it would be pretty useless. Instead, different Point objects can be instantiated with different values, which means the same code can be used for different situations.
Ok, so constructors instantiate or start a class by collecting all the data the class needs to start to start working. Constructors are so important that the dart compiler provides one even if you don't explicitly create one. For example, you create a class for mammals like this :
class Mammal{
String name = "cat";
int numberOfLegs = 2;
}
Although you don't explicitly add a constructor the dart compiler adds a default constructor like this :
class Mammal{
Mammal(); //This is added by dart during the class instantiation by default.
String name = "cat";
int numberOfLegs = 2;
}
Yeah, that's how crucial constructors are to the dart compiler.
And on the topic of why are they necessary even when you declare all the properties by yourself in the class, as hacker1024 said it would make the class pretty useless, as the point of the existence of classes is to create variants but with different properties. Not adding a constructor to your class and defining all the properties in the class would mean that your class doesn't take property arguments which in turn also means that different variants of your class can't be created. Again this goes directly against the point of the existence of dart classes. For example, you have a class like this :
class Mammals{
Strig name = "Human";
int numberOfLegs = 2;
bool hasFur = false;
}
final cat = Mammal();
final human = Mammal();
print(cat.numberOfLegs); //Prints 2
//2
print(human.numberOfLegs); //Also prints 2
//2
print(cat.hasFur);
// false
Yeah, this class is problematic. Cats with 2 legs? You would agree with me that that's not how things are in reality. And also the class is pretty useless in the sense that it's not modular, no matter which kind of mammal we create be it a cat, a sheep or even a cow the name property is going to be the default one we set, that is "Human". When we create a class to simulate mammals we want to be able to define what kind of properties it has, not use some fixed values. So you want to create a class which has a constructor like this :
class Mammals{
Mammals(String name,int noOfLegs, bool hasFur){
this.name = name;
this.noOfLegs = noOfLegs;
this.hasFur = hasFur;
}
String name = "";
int noOfLegs = 0;
bool hasFur = False;
}
final cat = Mammal("Cat", 4, True); //Now you can pass in the properties ou want.
final human = Mammal("Human", 2, false);
print(cat.name); //This prints the customized name of the object cat instead of some fixed value
//Cat
print(human.name); //This prints the customized name of the object human
Now we have two instances of the class with separate property values.
Although this adds a little more code, the modularity benefit is worth it.

Can I pass a type of enum as an argument in Dart?

I want to have a method that takes a parameter of type enum as a parameter and then operates on it to get all possible values of the enum type, and do some work with each of those values.
I'd be hoping for something like:
Widget foo (EnumType enumType) {
for(var value in enumType.values) {
print(value.name);
}
}
I've looked for solutions but the only ones I can find are addressed by passing a list of the values as a parm, however this doesn't solve my problem as, even with the list of objects, I can't know that they are enum values so if I try do the .name operation on them, dart throws an error Error: The getter 'name' isn't defined for the class 'Object'.
Maybe my only problem is that I don't know how to specify a variable as an EnumType but I haven't been able to find a correct type for this.
EnumType.values is the equivalent of an automatically generated static method on EnumType and as such is not part of any object's interface. You therefore will not be able to directly call .values dynamically.
I've looked for solutions but the only ones I can find are addressed by passing a list of the values as a [parameter], however this doesn't solve my problem as, even with the list of objects, I can't know that they are enum values so if I try do the .name operation on them, dart throws an error
You can use a generic function that restricts its type parameter to be an Enum:
enum Direction {
north,
east,
south,
west,
}
List<String> getNames<T extends Enum>(List<T> enumValues) =>
[for (var e in enumValues) e.name];
void main() {
print(getNames(Direction.values)); // Prints: [north, east, south, west]
}
The problem with enums is that they can't be passed as a parameter, what you can do instead is that pass all the values and then extract the name from the toString method.
void printEnumValues<T>(List<T> values){
for(var value in values){
final name = value.toString().split('.')[1];
print(name);
}
}
Also I would recommend you look into freezed union classes as that might allow you an alternative approach towards the problem you're trying to solve.

What's the access level of a case within a private enumeration

I read the document about Swift 5.1 from swift.org and have some questions about access level in enumeration.
https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html#ID14
In the document, it says:
The individual cases of an enumeration automatically receive the same access level as the enumeration they belong to.
private enum SomePrivateEnum {
case one
case two
case three
}
private class SomePrivateClass {
private var somePrivateProperty = 0
}
// work
print(SomePrivateEnum.one)
// error: 'somePrivateProperty' is inaccessible due to 'private' protection level
print(SomePrivateClass().somePrivateProperty)
According to the document, if I have a private enum, then all cases should receive private access level. The question is, why can I access the private case outside the enum declaration ? This behavior is different from Class.
First of all, your code is completely artificial, as it would not even compile except in a playground — and in a playground the concepts of privacy are more or less meaningless. Test only within a real project.
When you do, you will have something like this:
private enum SomePrivateEnum {
case one
case two
case three
}
private class SomePrivateClass {
private var somePrivateProperty = 0
}
class ViewController : UIViewController {
func test() {
print(SomePrivateEnum.one)
print(SomePrivateClass().somePrivateProperty)
}
}
Now that we've established that, we can proceed to what's wrong with your test itself, namely that you are comparing apples with oranges. Here's the parallelism:
print(SomePrivateEnum.one) // ok
print(SomePrivateClass()) // ok
So private for SomePrivateEnum and private for SomePrivateClass mean the same thing, namely: "private within this file". This code is in the same file so it can see both SomePrivateEnum and SomePrivateClass. (As the docs tell you, code that can see SomePrivateEnum can see SomePrivateEnum.one, and vice versa. So we are now comparing apples with apples.)
But private for somePrivateProperty means something else. It means "private within this type". So only code inside SomePrivateClass can see somePrivateProperty. This code is not inside SomePrivateClass, so it can't see that property.
You can access private declarations inside current context.
for example, if you wrap enum with other context - it will not be accessible same way as property inside SomePrivateClass.
i.e. this will be inaccessible:
struct Foo {
private enum SomePrivateEnum {
case one
case two
case three
}
}
print(Foo.SomePrivateEnum.one)
and this will be:
private class SomePrivateClass {
var somePrivateProperty = 0
}
print(SomePrivateClass().somePrivateProperty)

Unity3D & YamlDotNet Deserializing Data into Monobehaviour-derived classes

I'm trying to serialize data into / from my classes, derived from MonoBehaviour, which cannot be created from client code (e.g., with the new keyword), but rather must be created by a Unity3D-specific method, GameObject.AddComponent<T>(). How can I use the YamlDotNet framework to populate my classes with values without having to create an adapter for each one? Is there some sort of built-in adapter that I can configure, such that YamlDotNet doesn't instantiate the class it's trying to serialize to?
A typical file might contain a mapping of items, e.g.,
%YAML 1.1
%TAG !invt! _PathwaysEngine.Inventory.
%TAG !intf! _PathwaysEngine.Adventure.
---
Backpack_01: !invt!Item+yml
mass: 2
desc:
nouns: /^bag|(back)?pack|sack|container$/
description: |
Your backpack is only slightly worn, and...
rand_descriptions:
- "It's flaps twirl in the breeze."
- "You stare at it. You feel enriched."
MagLite_LR05: !invt!Lamp+yml
cost: 56
mass: 2
time: 5760
desc:
nouns: /^light|flashlight|maglite|lr_05$/
description: |
On the side of this flashlight is a label...
(Type "light" to turn it on and off.)
...
Where the tags are the fully specified class names of my Items, e.g., PathwaysEngine.Inventory.Lamp+yml, PathwaysEngine is the namespace I use for my game engine code, Inventory deals with items & whatnot, and Lamp+yml is how the compiler denotes a nested class, yml inside Lamp. Lamp+yml might look like this:
public partial class Lamp : Item, IWearable {
public new class yml : Item.yml {
public float time {get;set;}
public void Deserialize(Lamp o) {
base.Deserialize((Item) o);
o.time = time;
}
}
}
I call Deserialize() on all objects that derive from Thing from Awake(), i.e., once the MonoBehaviour classes exist in the game. Elsewhere, I've already created a pretty complicated Dictionary filled with objects of type Someclass+yml, and then Deserialize takes an instance of the real, runtime class Someclass and populates it with values. There's got to be a cleaner way to do this, right?
How can I:
Tell the Deserializer what my classes are?
See the second edit for a good solution for the above issue
Get the data without it attempting to create my MonoBehaviour-derived classes?
Edit: I've since worked at the problem, and have found out a good way of dealing with custom data (in my particular case of trying to parse regexes out of my data, and having them not be considered strings & therefore, un-castable to regex) is to use a IYamlTypeConverter for that particular string. Using YamlDotNet with Unity3D MonoBehaviours, however, is still an issue.
Another Edit: The above examples use a pretty ugly way of determining types. In my case, the best thing to do was to register the tags first with the deserializer, e.g.,
var pre = "tag:yaml.org,2002:";
var tags = new Dictionary<string,Type> {
{ "regex", typeof(Regex) },
{ "date", typeof(DateTime) },
{ "item", typeof(Item) }};
foreach (var tag in tags)
deserializer.RegisterTagMapping(
pre+tag.Key, tag.Value);
Then, I use the !!tag notation in the *.yml file, e.g.,
%YAML 1.1
---
Special Item: !!item
nouns: /thing|item|object/
someBoolean: true
Start Date: !!date 2015-12-17
some regex: !!regex /matches\s+whatever/
...
You can pass a custom implementation of IObjectFactory to the constructor of the Deserializer class. Every time the deserializer needs to create an instance of an object, it will use the IObjectFactory to create it.
Notice that your factory will be responsible for creating instances of every type that is deserialized. The easiest way to implement it is to create a decorator around DefaultObjectFactory, such as:
class UnityObjectFactory : IObjectFactory
{
private readonly DefaultObjectFactory DefaultFactory =
new DefaultObjectFactory();
public object Create(Type type)
{
// You can use specific types manually
if (type == typeof(MyCustomType))
{
return GameObject.AddComponent<MyCustomType>();
}
// Or use a marker interface
else if (typeof(IMyMarkerInterface).IsAssignableFrom(type))
{
return typeof(GameObject)
.GetMethod("AddComponent")
.MakeGenericMethod(type)
.Invoke();
}
// Delegate unknown types to the default factory
else
{
return DefaultFactory(type);
}
}
}

OOP Terminology: class, attribute, property, field, data member

I am starting studying OOP and I want to learn what constitutes a class. I am a little confused at how loosely some core elements are being used and thus adding to my confusion.
I have looked at the C++ class, the java class and I want to know enough to write my own pseudo class to help me understand.
For instance in this article I read this (.. class attribute (or class property, field, or data member)
I have seen rather well cut out questions that show that there is a difference between class property and class field for instance What is the difference between a Field and a Property in C#?
Depending on what language I am studying, is the definition of
Property
Fields
Class variables
Attributes
different from language to language?
"Fields", "class variables", and "attributes" are more-or-less the same - a low-level storage slot attached to an object. Each language's documentation might use a different term consistently, but most actual programmers use them interchangeably. (However, this also means some of the terms can be ambiguous, like "class variable" - which can be interpreted as "a variable of an instance of a given class", or "a variable of the class object itself" in a language where class objects are something you can manipulate directly.)
"Properties" are, in most languages I use, something else entirely - they're a way to attach custom behaviour to reading / writing a field. (Or to replace it.)
So in Java, the canonical example would be:
class Circle {
// The radius field
private double radius;
public Circle(double radius) {
this.radius = radius;
}
// The radius property
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
// We're doing something else besides setting the field value in the
// property setter
System.out.println("Setting radius to " + radius);
this.radius = radius;
}
// The circumference property, which is read-only
public double getCircumference() {
// We're not even reading a field here.
return 2 * Math.PI * radius;
}
}
(Note that in Java, a property foo is a pair of accessor methods called getFoo() and setFoo() - or just the getter if the property is read-only.)
Another way of looking at this is that "properties" are an abstraction - a promise by an object to allow callers to get or set a piece of data. While "fields" etc. are one possible implementation of this abstraction. The values for getRadius() or getCircumference() in the above example could be stored directly, or they could be calculated, it doesn't matter to the caller; the setters might or might not have side effects; it doesn't matter to the caller.
I agree with you, there's a lot of unnecessary confusion due to the loose definitions and inconsistent use of many OO terms. The terms you're asking about are used somewhat interchangeably, but one could say some are more general than others (descending order): Property -> Attributes -> Class Variables -> Fields.
The following passages, extracted from "Object-Oriented Analysis and Design" by Grady Booch help clarify the subject. Firstly, it's important to understand the concept of state:
The state of an object encompasses all of the (usually static) properties of the object plus the current (usually dynamic) values of each of these properties. By properties, we mean the totality of the object's attributes and relationships with other objects.
OOP is quite generic regarding certain nomenclature, as it varies wildly from language to language:
The terms field (Object Pascal), instance variable (Smalltalk), member object (C++), and slot (CLOS) are interchangeable, meaning a repository for part of the state of an object. Collectively, they constitute the object's structure.
But the notation introduced by the author is precise:
An attribute denotes a part of an aggregate object, and so is used during analysis as well as design to express a singular property of the class. Using the language-independent syntax, an attribute may have a name, a class, or both, and optionally a default expression: A:C=E.
Class variable: Part of the state of a class. Collectively, the class variables of a class constitute its structure. A class variable is shared by all instances of the same class. In C++, a class variable is declared as a static member.
In summary:
Property is a broad concept used to denote a particular characteristic of a class, encompassing both its attributes and its relationships to other classes.
Attribute denotes a part of an aggregate object, and so is used during analysis as well as design to express a singular property of the class.
Class variable is an attribute defined in a class of which a single copy exists, regardless of how many instances of the class exist. So all instances of that class share its value as well as its declaration.
Field is a language-specific term for instance variable, that is, an attribute whose value is specific to each object.
I've been doing oop for more than 20 years, and I find that people often use different words for the same things. My understanding is that fields, class variables and attributes all mean the same thing. However, property is best described by the stackoverflow link that you included in your question.
Generally fields, methods, static methods, properties, attributes and class (or static variables) do not change on a language basis... Although the syntax will probably change on a per language basis, they will be function in the way you would expect across languages (expect terms like fields/data members to be used interchangably across languages)
In C#....
A field is a variable that exists for a given instance of a class.
eg.
public class BaseClass
{
// This is a field that might be different in each instance of a class
private int _field;
// This is a property that accesses a field
protected int GetField
{
get
{
return _field;
}
}
}
Fields have a "visibility" this determines what other classes can see the field, so in the above example a private field can only be used by the class that contains it, but the property accessor provides readonly access to the field by subclasses.
A property lets you get (sometimes called an accessor) or set (sometimes called a mutator) the value of field... Properties let you do a couple of things, prevent writing a field for example from outside the class, change the visibility of the field (eg private/protected/public). A mutator allows you to provide some custom logic before setting the value of a field
So properties are more like methods to get/set the value of a field but provide more functionality
eg.
public class BaseClass
{
// This is a field that might be different in each instance of a class
private int _field;
// This is a property that accesses a field, but since it's visibility
// is protected only subclasses will know about this property
// (and through it the field) - The field and property in this case
// will be hidden from other classes.
protected int GetField
{
// This is an accessor
get
{
return _field;
}
// This is a mutator
set
{
// This can perform some more logic
if (_field != value)
{
Console.WriteLine("The value of _field changed");
_field = value;
OnChanged; // Call some imaginary OnChange method
} else {
Console.WriteLine("The value of _field was not changed");
}
}
}
}
A class or static variable is a variable which is the same for all instances of a class..
So, for example, if you wanted a description for a class that description would be the same for all instance of the class and could be accessed by using the class
eg.
public class BaseClass
{
// A static (or class variable) can be accessed from anywhere by writing
// BaseClass.DESCRIPTION
public static string DESCRIPTION = "BaseClass";
}
public class TestClass
{
public void Test()
{
string BaseClassDescription = BaseClass.DESCRIPTION;
}
}
I'd be careful when using terminology relating to an attribute. In C# it is a class that can be applied to other classes or methods by "decorating" the class or method, in other context's it may simply refer to a field that a class contains.
// The functionality of this attribute will be documented somewhere
[Test]
public class TestClass
{
[TestMethod]
public void TestMethod()
{
}
}
Some languages do not have "Attributes" like C# does (see above)
Hopefully that all makes sense... Don't want to overload you!
Firstly, you need to select a language. For example, I would recommend you to select Ruby language and community. Until you select a language, you cannot escape confusion, as different communities use different terms for the same things.
For example, what is known as Module in Ruby, Java knows as abstract class. What is known as attributes in some languages, is known as instance variables in Ruby. I recommend Ruby especially for its logical and well-designed OOP system.
Write the following in a *.rb file, or on the command line in irb (interactive Ruby interpreter):
class Dog # <-- Here you define a class representing all dogs.
def breathe # <-- Here you teach your class a method: #breathe
puts "I'm breathing."
end
def speak # <-- Here you teach your class another method: #speak
puts "Bow wow!"
end
end
Now that you have a class, you can create an instance of it:
Seamus = Dog.new
You have just created an instance, a particular dog of class Dog, and stored it in the constant Seamus. Now you can play with it:
Seamus.breathe # <-- Invoking #breathe instance method of Seamus
#=> I'm breathing.
Seamus.speak # <-- Invoking #speak instance method of Seamus
#=> Bow wow!
As for your remaining terminology questions, "property" or "attribute" is understood as "variable" in Ruby, almost always an instance variable. And as for the term "data member", just forget about it. The term "field" is not really used in Ruby, and "class variable" in Ruby means something very rarely used, which you definitely don't need to know at this moment.
So, to keep the world nice and show you that OOP is really simple and painless in Ruby, let us create an attribute, or, in Ruby terminology, an instance variable of Dog class. As we know, every dog has some weight, and different dogs may have different weights. So, upon creation of a new dog, we will require the user to tell us dog's weight:
class Dog
def initialize( weight ) # <-- Defining initialization method with one argument 'weight'
#weight = weight # <-- Setting the dog's attribute (instance variable)
end
attr_reader :weight # <-- Making the dog's weight attribute visible to the world.
end
Drooly = Dog.new( 16 ) # <-- Weight now must provide weight upon initialization.
Drooly.weight # <-- Now we can ask Drooly about his weight.
#=> 16
Remember, with Ruby (or Python), things are simple.
I discovered in my question that Properties as defined in .Net are just a convenience syntax for code, and they are not tied to underlying variables at all (except for Auto-Implemented Properties, of course). So, saying "what is the difference between class property and class field" is like saying: what is the difference between a method and an attribute. No difference, one is code and the other is data. And, they need not have anything to do with each other.
It is really too bad that the same words, like "attribute" and "property", are re-used in different languages and ideologies to have starkly different meanings. Maybe someone needs to define an object-oriented language to talk about concepts in OOP? UML?
In The Class
public class ClassSample
{
private int ClassAttribute;
public int Property
{
get { return ClassAttribute; }
set { ClassAttribute = value; }
}
}
In the Program
class Program
{
static void Main(string[] args)
{
var objectSample = new ClassSample();
//Get Object Property
var GetProperty = objectSample.Property;
}
}