When I should define operations-type-traits for a USTRUCT - unreal-engine4

For some USTRUCT structs within UnrealEngine, type traits TStructOpsTypeTraits<T> are defined. These provide a list of bools (encapsulated in an enumeration) about the implemented capabilities of struct T.
What is the usage of those traits?
When I should define those traits for my custom USTRUCTs within my project?
*Example usage from within the Engine:
struct TStructOpsTypeTraitsBase2
{
enum
{
WithZeroConstructor = false, // struct can be constructed as a valid object by filling its memory footprint with zeroes.
WithNoInitConstructor = false, // struct has a constructor which takes an EForceInit parameter which will force the constructor to perform initialization, where the default constructor performs 'uninitialization'.
WithNoDestructor = false, // struct will not have its destructor called when it is destroyed.
WithCopy = !TIsPODType<CPPSTRUCT>::Value, // struct can be copied via its copy assignment operator.
// ...
}
}
Which is used like
template<>
struct TStructOpsTypeTraits<FGameplayEffectContextHandle> : public TStructOpsTypeTraitsBase2<FGameplayEffectContextHandle>
{
enum
{
WithCopy = true, // Necessary so that TSharedPtr<FGameplayEffectContext> Data is copied around
WithNetSerializer = true,
WithIdenticalViaEquality = true,
};
};
It seems that traits are used for USTRUCTs that are used in blueprints; and that they are required for structs which have a NetSerialize() function. I made spot checks:
WithIdenticalViaEquality -> UScriptStruct::HasIdentical() -> EStructFlags::STRUCT_IdenticalNative is used only in ::IdenticalHelper() which is intended for Blueprints
EStructFlags::STRUCT_NetSerializeNative is used for error messages (when the structs are used in blueprints) and in FObjectReplicator and FRepLayout, where this trait is required to be present for custom property replication
the description of TStructOpsTypeTraitsBase2 seems to tell, that these traits are only important, when the USTRUCTs are used within blueprints
type traits to cover the custom aspects of a script struct
UnrealEngine defines also a number of specialized traits for its container classes (e.g. TTypeTraitsBase). A comparison with c++ type_traits might be meaningful.

Many of the features available "out-of-the-box" in Unreal Engine 4 (e.g. replication, initialization, serialization, etc.) rely on information specific to each class. This allows different classes to - for example - customize how to serialize their own data.
For classes inheriting from the base UObject class, all the needed information are stored into properties or returned by overridable methods. For example, if you want to customize how your UObject-derived class manages serialization, you can simply override its virtual Serialize() method. This is enough for UE4 to be able to invoke your custom implementation when it need to serialize an instance of your class.
The problem with structs in UE4, is that they don't inherit from a common base class/interface. So UE4 doesn't have any pre-declare property or method to call. Trying to call an undeclared method will of course cause a compilation error in C++. Following the previous example on the custom serialization - UE4 can't in general invoke the Serialize() method on structs because some/most of them will not have such method and the compiler will report it as an error.
TStructOpsTypeTraitsBase2 is the solution to the above problem. You declare a specialization of it for your custom structs to inform UE4 of which methods are available. When done, using a mix of template meta-programming and auto-generated code, UE4 will be able to call such methods to provide again out-of-the-box services or allow you to customize default behaviors. For example, declaring WithSerializer = true you're informing UE4 that your struct has a custom Serialize() method and so UE4 will be able to automatically call it every time it needs to serialize an instance of your struct.
TStructOpsTypeTraitsBase2 is not limited to structs used with Blueprints, but is used also with USTRUCT() used in C++.
On when to use it, you need to declare a custom specialization of TStructOpsTypeTraitsBase2 when the default behavior of UE4 on your structure is not what you want (e.g. you want to serialize its data in a different way while the default implementation serializes all the not-transient UPROPERTY() using "standard" formats).
While the "form" is similar, the scope of TStructOpsTypeTraitsBase2 is different than C++ type_traits: type_traits is used by the compiler to inform the program/programmer about platform characteristics. TStructOpsTypeTraitsBase2 is used by the programmer to inform UE4 about available "extra" features of a custom struct.

Related

Simple container bindings in Swift?

Disclaimer: I'm still learning Swift so forgive me if I haven't understood certain concepts/capabilities/limitations of Swift.
With the Swinject framework, if you wanted to bind a protocol to a class - it seems you have to return the class instance in a closure such as:
container.register(Animal.self) { _ in Cat() }
Is is possible to be able to instead pass in two types to the register() method and have the framework instantiate the class for you? It would need to recursively see if that class had any initializer dependencies of course (Inversion of Control).
This is possible in the PHP world as you have the concept of reflection, which allows you to get the class types of the dependencies, allowing you instantiate them on the fly. I wonder if Swift has this capability?
It would be much nicer to write this:
container.register(Animal.self, Cat.self)
This would also allow you to resolve any class from the container and have it's dependencies resolved also (without manually registering the class):
container.resolve(NotRegisteredClass.self)
Note: This only makes sense for classes that do not take scalar types as a dependency (as they need to be explicitly given of course).
The second case - resolving a type without the explicit registration - is currently not possible because of Swift's very limited support for the reflection.
However, there is a SwinjectAutoregistration extension which will enable you to write something very close to your first example:
container.autoregister(Animal.self, initializer: Cat.init)

Swift: Constant's internal implementation

In swift, how is constants implemented?
I read this article, which says
In Swift, constants are generally implemented as (inlined) function calls.
I am not clear of this statement.
Does Swift use a special approach to make constants?
Could anyone explain?
Are you familiar with "getter" and "setter" methods from other languages, such as Java? If a variable is made public in a language like Java, it's exposed to other classes to access directly. In the future, if this variable has to be changed, there's no way to do so without changing all of the other classes dependent upon. With getter/setter methods, dummy implementations can be made that don't do anything besides read/write the value. In the case that a change needs to be made, the implementation of these methods can be changed without effecting the public API of the class.
Swift implements variables with "properties", which are like a backing private variable with public getter/setter methods that are automatically generated. In the future, you can replace a property with a computer property with a special getter/setter implementation, without effecting the public API of the class, just like before. The difference here is that you don't need to write all of the default getters/setters yourself.

Typescript best practices : Interfaces versus Classes [duplicate]

In C# there's a quite huge difference between interfaces and classes. Indeed, a class represents a reference-type, so that we can actually create objects modeled on that class, while interfaces are meant to be contracts that a class sign to in order to ensure the existence of a certain behavior. In particular we can't create instances of interfaces.
The whole point with interfaces is to expose behavior. A class implements it by giving one explicit implementation of said behavior.
In that case, although interfaces may contain properties, most of the time we care about interfaces because of behavioral issues. So most of the type, interfaces are just contracts of behavior.
On TypeScript, on the other hand, I've seem something that made me quite uneasy, and in truth I've seen this more than once, which is the reason for this question.
In one tutorial I saw this:
export interface User {
name: string; // required with minimum 5 chracters
address?: {
street?: string; // required
postcode?: string;
}
}
But wait a minute. Why User is an interface? If we think like C#, User shouldn't be an interface. In truth, looking at it, it seems like we are defining the data type User, instead of a contract of behavior.
Thinking like we do in C#, the natural thing would be this:
export class User {
public name: string;
public address: Address;
}
export class Address {
public street: string;
public postcode: string;
}
But this thing of using interfaces like we do with classes, to just define a data type, rather than defining a contract of behavior, seems very common in TypeScript.
So what interfaces are meant for in TypeScript? Why do people use interfaces in TypeScript like we use clases in C#? How interfaces should be properly used in TypeScript: to establish contracts of behavior, or to define properties and object should have?
Consider that in Javascript, data is often exchanged as plain objects, often through JSON:
let data = JSON.parse(someString);
Let's say this data is an array of User objects, and we'll pass it to a function:
data.forEach(user => foo(user))
foo would be typed like this:
function foo(user: User) { ... }
But wait, at no point did we do new User! Should we? Should we have to write a class User and map all the data to it, even though the result would be exactly the same, an Object with properties? No, that would be madness just for the sake of satisfying the type system, but not change anything about the runtime. A simple interface which describes how the specific object is expected to look like (to "behave") is perfectly sufficient here.
I also came to Typescript from a C# background and have wondered the same things. I was thinking along the lines of POCOs (is POTO a thing?)
So what interfaces are meant for in TypeScript?
The Typescript Handbook seems to say that interfaces are meant for "defining contracts within your code".
Why do people use interfaces in TypeScript like we use classes in C#?
I agree with #deceze's answer here.
John Papa expands on the subject of classes and interfaces on his blog. He suggests that classes are best suited for "creating multiple new instances, using inheritance, [and] singleton objects". So, based on the intent of Typescript interfaces as described in the Typescript Handbook and one man's opinion, it would appear that classes are not necessary to establish contracts in Typescript. Instead, you should use interfaces. (Your C# senses will still be offended.)
Interfaces should be properly used in TypeScript: to establish contracts of behavior, or to define properties and object should have?
If I understand the question, you are asking if interfaces should establish contracts of behavior or contracts of structure. To this, I would answer: both. Typescript interfaces can still be used the same way interfaces are used in C# or Java (i.e. to describe the behavior of a class), but they also offer the ability to describe the structure of data.
Furthermore, my coworker got on me for using classes instead of interfaces because interfaces produce no code in the compiler.
Example:
This Typescript:
class Car implements ICar {
foo: string;
bar(): void {
}
}
interface ICar {
foo: string;
bar(): void;
}
produces this Javascript:
var Car = (function () {
function Car() {
}
Car.prototype.bar = function () {
};
return Car;
}());
Try it out
Interfaces in typescript are similar to interfaces in C# in that they both provide a contract. However opposed to C# interfaces which only contain methods typescript interfaces can also describe fields or properties that objects contain. Therefore they can also be used for things which are not directly possible with C# interfaces.
A major difference between interfaces and classes in typescript is that interfaces don't have a runtime representation and there won't be any code emitted for them. Interfaces are very broadly usable. For example you can use object literals to construct objects with satisfy an interface. Like:
let user: User = {
name: 'abc',
address: {
street: 'xyz',
},
};
Or you can assign any data objects (e.g. received through JSON parsing) to an interface (but your pre-checks should assert that it's really valid data). Therefore interfaces are very flexible for data.
On the other hand classes have a type associated at runtime to them and there is code generated. You can check the type at runtime with instanceof and there's a prototype chain set up. If you define User as a class it won't be a valid user unless you call the constructor function. And you can't just define any kind of suitable data to be a User. You would need to create a new instance and copy the properties over.
My personal rule of thumb:
If I'm dealing with pure data (of varying sources) I use interfaces
If I'm modelling something which has an identity and state (and probably attached methods to modify the state) I'm using a class.
How interfaces should be properly used in TypeScript: to establish contracts of behavior, or to define properties and object should have?
Interfaces in TypeScript are shape contracts, describing the expected structure of an object. If a value has a certain interface annotation, you expect it to be an object featuring the members defined in the interface. Members can be values or functions (methods). Generally, their behavior (function bodies) is not part of the contract. But you can specify if they are readonly or not.
So what interfaces are meant for in TypeScript? Why do people use interfaces in TypeScript like we use clases in C#?
Typescript interfaces can play the same role as C# interfaces if they are expected to be implemented by TypeScript classes.
But not only a class can implement an interface; any kind of value can:
interface HelloPrinter {
printHello(): void
}
The following object is not a class but nevertheless implements the interface:
{
printHello: () => console.log("hello")
}
Thus we can do
const o: HelloPrinter = {
printHello: () => console.log("hello")
}
and the TypeScript compiler won't complain.
The object implements our interface without forcing us to write a class.
Working with interfaces is more lightweight than working with (interfaces and) classes.
But if you need to know the type name (class/interface name) during runtime then classes are the right choice, because interface names are only known at compile time.
Using only the native deserialization mechanism, you cannot deserialize an instance of a specific class. You can only deserialize into a plain-old-javascript-object. Such objects can adhere to typescript interfaces but cannot be an instance of a class. If you need to deal with data that crosses a serialization boundary such as data expected from a webservice, use interfaces. If you need to generate new instances of such values yourself, just construct them literally or create a convenience function that returns them - objects that adhere to that interface.
A class can itself implement an interface, but it might get confusing if you expect to deal with both locally constructed class instances AND deserialized, reconstituted plain objects. You'd never be able to rely on the class-basis of the object and so there'd be no benefit of also defining it as a class for that exact purpose.
I've had success in creating a ServerProxy module responsible for sending code back and forth from a webservice - the webservice call and the returned result. If you're binding to knockout models or similar, you can have a class that encapsulates the ui-bound model with a constructor that knows how to lift a returned plain-old-javascript-object that adheres to the webservice's interface-only contract into an instance of your model class.

Swift: access level between `private` and `internal`?

In my Swift code, I often use the private modifier to limit the visibility of helper classes. For example, in one file, I'll have a GridController and a GridControllerModel.
The GridController (the UI) should be accessible to the rest of the application, but the model class is wholly internal and should never be accessed by the rest of the application.
I can address this in Swift by making both classes private and keeping them in the same file. But this gets unwieldy as classes get bigger. What I'd like to do is keep each class in a separate file (for programming convenience), but prevent access to the model class anything but GridController (for information hiding purposes).
Is there any way to do this in Swift?
As others have said, there is no way to do exactly what you want today in Swift.
One alternative is to use an extension in another file to add GridControllerModel as a nested subtype of GridController. e.g.
//GridControllerModel.swift
extension GridController {
struct GridControllerModel {
let propertyOne:String
let propertyTwo:String
}
}
This allows your GridController class in its own separate file to declare something like:
var model = GridControllerModel()
However, the rest of the application can still access the GridControllerModel type like this:
//SomeOtherClass.swift
var nested = GridController.GridControllerModel()
So, you do achieve some separation by making the model type a subtype of GridController, but it isn't true access control. On the plus side, it will not appear in code completion outside of the GridController class as "GridControllerModel", you would need to first type "GridController" and then "." to see the subtype "GridController.GridControllerModel"
It's also worth noting that an additional access control level is currently under review and likely to be in the next version of Swift (3.0) :
https://github.com/apple/swift-evolution/blob/master/proposals/0025-scoped-access-level.md
Assuming this proposal is accepted and implemented, you would be able to update your declared subtype like this:
//GridControllerModel.swift
local extension GridController {
struct GridControllerModel {
let propertyOne:String
let propertyTwo:String
}
}
(Note the "local" keyword above now). This would make the GridControllerModel type invisible and inaccessible to all classes except GridController and any extensions of GridController.
So, I would recommend that you consider this nested subtype approach today, because when Swift 3.0 arrives later this year, it's likely to support what you want by simply adding a keyword in front of your subtype declaration. And in the meantime, you get some of the separation you want as well.
No, there isn't an access modifier that restricts visibility to only a certain set of files. But you probably don't need that.
What does exist:
private: restricts visibility to within the same source file.
internal: restricts visibility to within the same module.
If you're building a piece of software that's too big for one source file, but both defines an outward-facing interface and internal details that should stay hidden from clients of that interface... then you're probably working at a level where it's appropriate to build a framework. Your framework can then define features that are internal for its use only and separate from the public interface it exposes to clients.

gtk _get_type() function implementation

I just started learning GTK. I was going through source code of gtk+3.0.0, I found implementation of _get_type() methods for some gtk object types but some do not have an implementation of this method e.g GtkRange. Is there any reason for this? As far I understood from GObject Reference Manual, _get_type() method registers object type in type system.
the get_type() function is needed for all types registered as a GType. GObject (the library) provides convenience macros to generate the correct get_type() function implementation taking into account things like thread-safe initialization, or dynamic type registration.
the macro that is used for GObject (the type) subclasses is G_DEFINE_TYPE(), but inside GTK+ you will also find G_DEFINE_TYPE_WITH_CODE(), used generally when the type also implements interfaces; G_DEFINE_ABSTRACT_TYPE() and G_DEFINE_ABSTRACT_TYPE_WITH_CODE(), used for abstract types; and, more recently, G_DEFINE_TYPE_WITH_PRIVATE() and G_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE(), which define GObject subclasses with private data, avoiding the call to g_type_class_add_private() inside the class initialization function.
boxed types (GType wrappers around Plain Old Structures) also have G_DEFINE_BOXED_TYPE(), and interface types have G_DEFINE_INTERFACE().
more information is available in the API reference for GObject:
https://docs.gtk.org/gobject/func.DEFINE_TYPE.html