Add constructor to a struct; lose array initialization? - constructor

This works...
struct FOO
{
char bar1[50 + 1];
char bar2[50 + 1];
};
FOO foo[] =
{
{"baz1", "baz2"},
{"baz3", "baz4"}
};
But this does not...
struct FOO2
{
FOO2(void) { };
char bar1[50 + 1];
char bar2[50 + 1];
};
FOO2 foo2[] =
{
{"baz1", "baz2"},
{"baz3", "baz4"}
};
Morover, this...
struct FOO3
{
void init(void) { };
char bar1[50 + 1];
char bar2[50 + 1];
};
FOO3 foo3[] =
{
{"baz1", "baz2"},
{"baz3", "baz4"}
};
...works too.
So, methods don't disallow array initialization but a constructor does.
From Microsoft's error description these attributes (among others) cause an entity to become a "non-aggregate" and therefore no longer a valid target for array initialization:
Constructors
Private or protected members
Base classes
Virtual functions
Why, in the case of constructors?

Related

boost shared_memory_object use of deleted function

use of deleted function in class operator=
old version worked with old compiler but not with new versions
I need this "operator=" overloading for container operation.
#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>
using namespace boost::interprocess;
class X {
public:
size_t m_len;
shared_memory_object m_shm;
const char* m_ptr;
X():
m_len(0),
m_shm(shared_memory_object()),
m_ptr(nullptr){}
X(size_t t, const char* n):
m_len(t),
m_shm(shared_memory_object()),
m_ptr(nullptr){
shared_memory_object::remove(n);
m_shm = shared_memory_object(open_or_create,n, read_write);
m_shm.truncate (m_len);
mapped_region region(m_shm, read_write);
m_ptr = static_cast<char*>(region.get_address());
}
X(const X&& x){
m_len = x.m_len;
m_shm = x.m_shm; //error use deleted function
m_ptr = x.m_ptr;
}
virtual ~X(){}
X& operator = (const X&& a) {
if(&a == this) return *this;
m_len = a.m_len;
m_ptr = a.m_ptr;
m_shm = a.m_shm; //error use deleted function
return (*this);
}
const char* get_name(){
return m_shm.get_name();
}
};
int main ()
{
X a = X(22, "test");
X b = a; //Error
return 0;
};
The above class will be used in std::vector and operator= is needed.
boost shared_memory_object has member:
shared_memory_object(shared_memory_object &&);
shared_memory_object& operator=(shared_memory_object &&);
Move operations can only work on non-const objects. Why? Because it steals resources from the source instance, then it must be non-const to be modifiable. So your move operations should take non-const objects:
now should be
----------------------------------------------------------
X(const X&& x) ==> X(X&& x)
X& operator = (const X&& a) { ==> X& operator = (X&& a) {
Named variable is treated as L-value, it implies copy operations are called. You need to use std::move to cast source to R-value reference, then move operations can be called:
m_shm = std::move(x.m_shm); // in move ctor
m_shm = std::move(a.m_shm); // in move assignment operator
and finally to call move ctor:
X b = std::move(a);

How do I initialize a final class property in a constructor?

In Java you are allowed to do this:
class A {
private final int x;
public A() {
x = 5;
}
}
In Dart, I tried:
class A {
final int x;
A() {
this.x = 5;
}
}
I get two compilation errors:
The final variable 'x' must be initialized.
and
'x' can't be used as a setter because its final.
Is there a way to set final properties in the constructor in Dart?
You cannot instantiate final fields in the constructor body. There is a special syntax for that:
class Point {
final num x;
final num y;
final num distanceFromOrigin;
// Old syntax
// Point(x, y) :
// x = x,
// y = y,
// distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
// New syntax
Point(this.x, this.y) :
distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}
You can make it even shorter with this. syntax in the constructor (described in https://www.dartlang.org/guides/language/language-tour#constructors):
class Point {
final num x;
final num y;
final num distanceFromOrigin;
Point(this.x, this.y)
: distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
}
If you have some more complicated initialization you should use factory constructor, and the code become:
class Point {
final num x;
final num y;
final num distanceFromOrigin;
Point._(this.x, this.y, this.distanceFromOrigin);
factory Point(num x, num y) {
num distance = distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2));
return new Point._(x, y, distance);
}
}
Here is a simplified summary of the ways to initialize a final class variable.
class MyClass {
final int x; // <-- initialize this
}
Initializer value
class MyClass {
final int x = 'hello'.length;
}
You'd only use final if the initialization could only be done at runtime. Otherwise, static const is better:
class MyClass {
static const int x = 0;
}
Initializer formal
class MyClass {
MyClass(this.x);
final int x;
}
This is the most common approach.
Initializer list
class MyClass {
MyClass(int x)
: _x = x;
final int _x;
}
This is useful when you want to keep a field private.
Default parameter value
You can surround the parameter with square brackets ([]) for an unnamed parameter or curly braces ({}) for a named parameter and then give it a default value.
class MyClass {
MyClass({this.x = 0});
final int x;
}
This is useful if you want to make the parameter optional.
You could accomplish the same thing with an initializer list as well:
class MyClass {
MyClass({int? x})
: _x = x ?? 0;
final int _x;
}
Late initialization
class MyClass {
MyClass(String? a) {
x = a?.length ?? 0;
}
late final int x;
}
This is useful if you need to do more complex initialization than is allowed in the initializer list. For example, I've done this when initializing a gesture recognizer in Flutter.
Lazy initialization
Another advantage of using late is that it doesn't initialize a value until you access the value.
class MyClass {
late final int x = _doHeavyTask();
int _doHeavyTask() {
var sum = 0;
for (var i = 0; i < 100000000; i++) {
sum += 1;
}
return sum;
}
}
This is useful if you have a heavy calculation that you only want call if you absolutely need it.
This doesn't initialize x:
final myClass = MyClass();
But this does initialize x:
final myClass = MyClass();
final value = myClass.x;
I've had a similar problem: I was trying to initialise a final field from the constructor, while simultaneously calling a super constructor. You could think of the following example
class Point2d {
final int x;
final int y;
Point2d.fromCoordinates(Coordinates coordinates)
: this.x = coordinates.x,
this.y = coordinates.y;
}
class Point3d extends Point2d {
final int z;
Point3d.fromCoordinates(Coordinates coordinates)
:this.z = coordinates.z,
super.fromCoordinates(coordinates);
}
/// Demo class, to simulate constructing an object
/// from another object.
class Coordinates {
final int x;
final int y;
final int z;
}
Well apparently this works. You can initialise your final fields by using the above syntax (check Point3d's constructor) and it works just fine!
Run a small program like this to check:
void main() {
var coordinates = Coordinates(1, 2, 3);
var point3d = Point3d.fromCoordinates(coordinates);
print("x: ${point3d.x}, y: ${point3d.y}, z: ${point3d.z}");
}
It should prin x: 1, y: 2, z: 3
I've come to a dilemma here where I wanted to initialize a final List with no items, and a Stream to be defined inside the constructor (like in this case distanceFromOrigin).
I couldn't do that with any of the answers below, but I mixed them both and it worked.
Example:
class MyBloc {
final BehaviorSubject<List<String>> itemsStream;
final List<String> items = [];
MyBloc() : this.itemsStream = BehaviorSubject<List<String>>.seeded([]) {
items.addAll(List.generate(20, (index) => "Hola! I'm number $index"));
itemsStream.add(items);
}
}
class A{
final int x;
A(this.x){
}
}

Call constructor on TypeScript class without new

In JavaScript, I can define a constructor function which can be called with or without new:
function MyClass(val) {
if (!(this instanceof MyClass)) {
return new MyClass(val);
}
this.val = val;
}
I can then construct MyClass objects using either of the following statements:
var a = new MyClass(5);
var b = MyClass(5);
I've tried to achieve a similar result using the TypeScript class below:
class MyClass {
val: number;
constructor(val: number) {
if (!(this instanceof MyClass)) {
return new MyClass(val);
}
this.val = val;
}
}
But calling MyClass(5) gives me the error Value of type 'typeof MyClass' is not callable. Did you mean to include 'new'?
Is there any way I can make this pattern work in TypeScript?
What about this? Describe the desired shape of MyClass and its constructor:
interface MyClass {
val: number;
}
interface MyClassConstructor {
new(val: number): MyClass; // newable
(val: number): MyClass; // callable
}
Notice that MyClassConstructor is defined as both callable as a function and newable as a constructor. Then implement it:
const MyClass: MyClassConstructor = function(this: MyClass | void, val: number) {
if (!(this instanceof MyClass)) {
return new MyClass(val);
} else {
this!.val = val;
}
} as MyClassConstructor;
The above works, although there are a few small wrinkles. Wrinkle one: the implementation returns MyClass | undefined, and the compiler doesn't realize that the MyClass return value corresponds to the callable function and the undefined value corresponds to the newable constructor... so it complains. Hence the as MyClassConstructor at the end. Wrinkle two: the this parameter does not currently narrow via control flow analysis, so we have to assert that this is not void when setting its val property, even though at that point we know it can't be void. So we have to use the non-null assertion operator !.
Anyway, you can verify that these work:
var a = new MyClass(5); // MyClass
var b = MyClass(5); // also MyClass
Hope that helps; good luck!
UPDATE
Caveat: as mentioned in #Paleo's answer, if your target is ES2015 or later, using class in your source will output class in your compiled JavaScript, and those require new() according to the spec. I've seen errors like TypeError: Class constructors cannot be invoked without 'new'. It is quite possible that some JavaScript engines ignore the spec and will happily accept function-style calls also. If you don't care about these caveats (e.g., your target is explicitly ES5 or you know you're going to run in one of those non-spec-compliant environments), then you definitely can force TypeScript to go along with that:
class _MyClass {
val: number;
constructor(val: number) {
if (!(this instanceof MyClass)) {
return new MyClass(val);
}
this.val = val;
}
}
type MyClass = _MyClass;
const MyClass = _MyClass as typeof _MyClass & ((val: number) => MyClass)
var a = new MyClass(5); // MyClass
var b = MyClass(5); // also MyClass
In this case you've renamed MyClass out of the way to _MyClass, and defined MyClass to be both a type (the same as _MyClass) and a value (the same as the _MyClass constructor, but whose type is asserted to also be callable like a function.) This works at compile-time, as seen above. Whether your runtime is happy with it is subject to the caveats above. Personally I'd stick to the function style in my original answer since I know those are both callable and newable in es2015 and later.
Good luck again!
UPDATE 2
If you're just looking for a way of declaring the type of your bindNew() function from this answer, which takes a spec-conforming class and produces something which is both newable and callable like a function, you can do something like this:
function bindNew<C extends { new(): T }, T>(Class: C & {new (): T}): C & (() => T);
function bindNew<C extends { new(a: A): T }, A, T>(Class: C & { new(a: A): T }): C & ((a: A) => T);
function bindNew<C extends { new(a: A, b: B): T }, A, B, T>(Class: C & { new(a: A, b: B): T }): C & ((a: A, b: B) => T);
function bindNew<C extends { new(a: A, b: B, d: D): T }, A, B, D, T>(Class: C & {new (a: A, b: B, d: D): T}): C & ((a: A, b: B, d: D) => T);
function bindNew(Class: any) {
// your implementation goes here
}
This has the effect of correctly typing this:
class _MyClass {
val: number;
constructor(val: number) {
this.val = val;
}
}
type MyClass = _MyClass;
const MyClass = bindNew(_MyClass);
// MyClass's type is inferred as typeof _MyClass & ((a: number)=> _MyClass)
var a = new MyClass(5); // MyClass
var b = MyClass(5); // also MyClass
But beware the the overloaded declarations for bindNew() don't work for every possible case. Specifically it works for constructors which take up to three required parameters. Constructors with optional paramaters or multiple overload signatures will probably not be properly inferred. So you might have to tweak the typings depending on use case.
Okay, hope that helps. Good luck a third time.
UPDATE 3, AUG 2018
TypeScript 3.0 introduced tuples in rest and spread positions, allowing us to easily deal with functions of an arbitrary number and type of arguments, without the above overloads and restrictions. Here's the new declaration of bindNew():
declare function bindNew<C extends { new(...args: A): T }, A extends any[], T>(
Class: C & { new(...args: A): T }
): C & ((...args: A) => T);
The keyword new is required for ES6 classes:
However, you can only invoke a class via new, not via a function call (Sect. 9.2.2 in the spec) [source]
Solution with instanceof and extends working
The problem with most of the solution I've seen to
use x = X() instead of x = new X()
are:
x instanceof X doesn't work
class Y extends X { } doesn't work
console.log(x) prints some other type than X
sometimes additionally x = X() works but x = new X() doesn't
sometimes it doesn't work at all when targeting modern platforms (ES6)
My solutions
TL;DR - Basic usage
Using the code below (also on GitHub - see: ts-no-new) you can write:
interface A {
x: number;
a(): number;
}
const A = nn(
class A implements A {
x: number;
constructor() {
this.x = 0;
}
a() {
return this.x += 1;
}
}
);
or:
class $A {
x: number;
constructor() {
this.x = 10;
}
a() {
return this.x += 1;
}
}
type A = $A;
const A = nn($A);
instead of the usual:
class A {
x: number;
constructor() {
this.x = 0;
}
a() {
return this.x += 1;
}
}
to be able to use either a = new A() or a = A()
with working instanceof, extends, proper inheritance and support for modern compilation targets (some solutions only work when transpiled to ES5 or older because they rely on class translated to function which have different calling semantics).
Full examples
#1
type cA = () => A;
function nonew<X extends Function>(c: X): AI {
return (new Proxy(c, {
apply: (t, _, a) => new (<any>t)(...a)
}) as any as AI);
}
interface A {
x: number;
a(): number;
}
const A = nonew(
class A implements A {
x: number;
constructor() {
this.x = 0;
}
a() {
return this.x += 1;
}
}
);
interface AI {
new (): A;
(): A;
}
const B = nonew(
class B extends A {
a() {
return this.x += 2;
}
}
);
#2
type NC<X> = { new (): X };
type FC<X> = { (): X };
type MC<X> = NC<X> & FC<X>;
function nn<X>(C: NC<X>): MC<X> {
return new Proxy(C, {
apply: (t, _, a) => new (<any>t)(...a)
}) as MC<X>;
}
class $A {
x: number;
constructor() {
this.x = 0;
}
a() {
return this.x += 1;
}
}
type A = $A;
const A: MC<A> = nn($A);
Object.defineProperty(A, 'name', { value: 'A' });
class $B extends $A {
a() {
return this.x += 2;
}
}
type B = $B;
const B: MC<B> = nn($B);
Object.defineProperty(B, 'name', { value: 'B' });
#3
type NC<X> = { new (): X };
type FC<X> = { (): X };
type MC<X> = NC<X> & FC<X>;
function nn<X>(C: NC<X>): MC<X> {
return new Proxy(C, {
apply: (t, _, a) => new (<any>t)(...a)
}) as MC<X>;
}
type $c = { $c: Function };
class $A {
static $c = A;
x: number;
constructor() {
this.x = 10;
Object.defineProperty(this, 'constructor', { value: (this.constructor as any as $c).$c || this.constructor });
}
a() {
return this.x += 1;
}
}
type A = $A;
var A: MC<A> = nn($A);
$A.$c = A;
Object.defineProperty(A, 'name', { value: 'A' });
class $B extends $A {
static $c = B;
a() {
return this.x += 2;
}
}
type B = $B;
var B: MC<B> = nn($B);
$B.$c = B;
Object.defineProperty(B, 'name', { value: 'B' });
#2 simplified
type NC<X> = { new (): X };
type FC<X> = { (): X };
type MC<X> = NC<X> & FC<X>;
function nn<X>(C: NC<X>): MC<X> {
return new Proxy(C, {
apply: (t, _, a) => new (<any>t)(...a)
}) as MC<X>;
}
class $A {
x: number;
constructor() {
this.x = 0;
}
a() {
return this.x += 1;
}
}
type A = $A;
const A: MC<A> = nn($A);
class $B extends $A {
a() {
return this.x += 2;
}
}
type B = $B;
const B: MC<B> = nn($B);
#3 simplified
type NC<X> = { new (): X };
type FC<X> = { (): X };
type MC<X> = NC<X> & FC<X>;
function nn<X>(C: NC<X>): MC<X> {
return new Proxy(C, {
apply: (t, _, a) => new (<any>t)(...a)
}) as MC<X>;
}
class $A {
x: number;
constructor() {
this.x = 10;
}
a() {
return this.x += 1;
}
}
type A = $A;
var A: MC<A> = nn($A);
class $B extends $A {
a() {
return this.x += 2;
}
}
type B = $B;
var B: MC<B> = nn($B);
In #1 and #2:
instanceof works
extends works
console.log prints correctly
constructor property of instances point to the real constructor
In #3:
instanceof works
extends works
console.log prints correctly
constructor property of instances point to the exposed wrapper (which may be an advantage or disadvantage depending on the circumstances)
The simplified versions don't provide all meta-data for introspection if you don't need it.
See also
My answer to: In TypeScript, can a class be used without the "new" keyword?
My GitHub repo with more examples: https://github.com/rsp/ts-no-new
My workaround with a type and a function:
class _Point {
public readonly x: number;
public readonly y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
export type Point = _Point;
export function Point(x: number, y: number): Point {
return new _Point(x, y);
}
or with an interface:
export interface Point {
readonly x: number;
readonly y: number;
}
class _PointImpl implements Point {
public readonly x: number;
public readonly y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
export function Point(x: number, y: number): Point {
return new _PointImpl(x, y);
}
TL;DR
If you are targeting ES6 and you really want to use class to store your data, not a function:
Create a function that simply invokes your class constructor with its arguments;
Set that function's prototype to the prototype of your class.
From now you are able to call that function either with or without new keyword to generate new class instances.
Typescript playground
Typescript provides an ability to create such a function (let's call it a "callable constructor") in a strongly typed way. Well, any type is necessary in intermediate type definitions (replacing it with unknown causes errors), but this fact will not affect your experience.
First of all we need to define basic types to describe entities we are working with:
// Let's assume "class X {}". X itself (it has type "typeof X") can be called with "new" keyword,
// thus "typeof X" extends this type
type Constructor = new(...args: Array<any>) => any;
// Extracts argument types from class constructor
type ConstructorArgs<TConstructor extends Constructor> =
TConstructor extends new(...args: infer TArgs) => any ? TArgs : never;
// Extracts class instance type from class constructor
type ConstructorClass<TConstructor extends Constructor> =
TConstructor extends new(...args: Array<any>) => infer TClass ? TClass : never;
// This is what we want: to be able to create new class instances
// either with or without "new" keyword
type CallableConstructor<TConstructor extends Constructor> =
TConstructor & ((...args: ConstructorArgs<TConstructor>) => ConstructorClass<TConstructor>);
The next step is to write a function that accepts regular class constructors and creates corresponding "callable constructors".
function CreateCallableConstructor<TConstructor extends Constructor>(
type: TConstructor
): CallableConstructor<TConstructor> {
function createInstance(
...args: ConstructorArgs<TConstructor>
): ConstructorClass<TConstructor> {
return new type(...args);
}
createInstance.prototype = type.prototype;
return createInstance as CallableConstructor<TConstructor>;
}
Now all we have to do is to create our "callable constructor" and check it really works.
class TestClass {
constructor(readonly property: number) { }
}
const CallableTestConstructor = CreateCallableConstructor(TestClass);
const viaCall = CallableTestConstructor(56) // inferred type is TestClass
console.log(viaCall instanceof TestClass) // true
console.log(viaCall.property) // 56
const viaNew = new CallableTestConstructor(123) // inferred type is TestClass
console.log(viaNew instanceof TestClass) // true
console.log(viaNew.property) // 123
CallableTestConstructor('wrong_arg'); // error
new CallableTestConstructor('wrong_arg'); // error
I like #N. Kudryavtsev solution for creation smart instance factories (constructor wrapping with CreateCallableConstructor). But simple Reflect.construct(type, args) works perfectly if using any[] args is enough.
Here is the example with mobx (v5), which shows that there is no problems with prototypes and decorators:
import { observable, reaction } from "mobx";
class TestClass {
#observable
stringProp: string;
numProp: number;
constructor(data: Partial) {
if (data) {
Object.assign(this, data);
}
}
}
var obj = Reflect.construct(TestClass, [{numProp: 123, stringProp: "foo"}]) as TestClass;
// var obj = new TestClass({numProp: 123, stringProp: "foo"});
console.log(JSON.stringify(obj));
reaction(() => obj.stringProp, v => {
console.log(v);
}
);
obj.stringProp = "bar";
And even this simple wrapper functions works:
type Constructor = new (...args: any[]) => any;
const createInstance = (c: Constructor, ...args) => new c(...args);
var obj = createInstance(TestClass, {numProp: 123, stringProp: "foo"});
// or
const createInstance1 = (c: Constructor) => (...args) => new c(...args);
var obj1 = createInstance(TestClass)({numProp: 123, stringProp: "foo"}, 'bla');
Here's how I've solved this in jest for testing groups of immutable models. The makeHash function isn't doing anything special, just a utility creating short, random strings from uuid().
The 'magic' for me was declaring type as new (...args: any[]) => any allowing it to be 'newed' as let model = new set.type(...Object.values(set.args));. So, less about getting around new and more about working in 'newable' forms.
// models/oauth.ts
export class OAuthEntity<T = string> {
constructor(public readonly id: T) {}
[key: string]: any;
}
export class OAuthClient extends OAuthEntity {
/**
* An OAuth Client
* #param id A unique string identifying the client.
* #param redirectUris Redirect URIs allowed for the client. Required for the authorization_code grant.
* #param grants Grant types allowed for the client.
* #param accessTokenLifetime Client-specific lifetime of generated access tokens in seconds.
* #param refreshTokenLifetime Client-specific lifetime of generated refresh tokens in seconds
* #param userId The user ID for client credential grants
*/
constructor(
public readonly id: string = '',
public readonly redirectUris: string[] = [],
public readonly grants: string[] = [],
public readonly accessTokenLifetime: number = 0,
public readonly refreshTokenLifetime: number = 0,
public readonly userId?: string,
public readonly privateKey?: string
) {
super(id);
}
}
// models/oauth.test.ts
import { makeHash, makePin } from '#vespucci/utils';
import { OAuthEntity, OAuthClient } from '#vespucci/admin/server/models/oauth';
type ModelData = { type: new (...args: any[]) => any; args: { [key: string]: any }; defs?: { [key: string]: any } };
describe('Model Tests', () => {
const dataSet: ModelData[] = [
{ type: OAuthEntity, args: { id: makeHash() } },
{
type: OAuthClient,
args: {
id: makeHash(),
redirectUris: [makeHash()],
grants: [makeHash()],
accessTokenLifetime: makePin(2),
refreshTokenLifetime: makePin(2),
userId: makeHash(),
privateKey: makeHash(),
},
},
{
type: OAuthClient,
args: {},
defs: {
id: '',
redirectUris: [],
grants: [],
accessTokenLifetime: 0,
refreshTokenLifetime: 0,
},
},
];
dataSet.forEach((set) => {
it(`Creates ${set.type.name} With ${Object.keys(set.args).length} Args As Expected`, () => {
let model!: any;
const checkKeys = Object.keys(set.args).concat(Object.keys(set.defs || {}).filter((k) => !(k in set.args)));
const checkValues: any = checkKeys
.map((key) => ({ [key]: set.args[key] || set.defs?.[key] }))
.reduce((p, c) => ({ ...p, ...c }), {});
expect(() => {
model = new set.type(...Object.values(set.args));
}).not.toThrow();
expect(model).toBeDefined();
checkKeys.forEach((key) => expect(model[key]).toEqual(checkValues[key]));
});
});
});
The end result, for me, is:
You can use const obj = Object.create(MyClass.prototype) and then assign the values you want with Object.assign(obj, { foo: 'bar' })
This creates a class instance without using the new keyword or the constructor.

Refering within the class to constructor with the this pointer

#include "stdafx.h"
ref class station{
public:
station(){
};
void wrapper_1()
{
this->somefunct(); /*happy*/
};
void wrapper_2()
{
this->station(); /*not happy*/
};
void somefunct(){
System::Console::WriteLine(L"abcde");
};
};
int main(array<System::String^>^ args)
{
station^ temp_1 = gcnew station();
temp_1->wrapper_1();
System::Console::ReadLine();
};
I want to use the this pointer to call my constructor within my station class, it doesn't like this and throws the following error:
error C2273: 'function-style cast' : illegal as right side of '->'
operator.
Can someone explain to me how the constructor differs to other functions when using the pointer this to point to the function. I don't want to take the easy way out using station::station();
example of what I meant to #hans-passant
#include "stdafx.h"
ref class station{
public:
station(int par_1,int par_2)
{
int sum = par_1 + par_2;
System::Console::WriteLine(System::Convert::ToString(sum));
//default value output 13
};
station(){
int pass_1 = 5;
int pass_2 = 8;
station(pass_1,pass_2); /* But why couldn't I use this->station(pass_1,pass_2);*/
};
};
int main(array<System::String^>^ args)
{
station^ obj = gcnew station();
System::Console::ReadLine();
};

D compile-time function type extraction

D2.056
Function is a struct holding the name and the type of the function (Name and Type respectively). Binds iterates over a list of Function structs and returns a mixin string. This mixin defines for each function a new name with a '2' appended.
void f() { writeln("f"); }
void g() { writeln("g"); }
struct Function(string name, Prototype)
{
const string Name = name;
mixin("alias Prototype Type;");
}
string Binds(Functions...)()
{
string r;
foreach (F; Functions)
{
// error:
r ~= to!string(typeid(F.Type)) ~ " " ~ F.Name ~ "2 = &" ~ F.Name ~ ";";
}
return r;
}
int main()
{
mixin (Binds!(
Function!("f", void function()),
Function!("g", void function())
));
f();
//f2();
return 0;
}
When compiling, the to!string(typeid(F.Type)) gives an error:
Error: Cannot interpret & D13TypeInfo_PFZv6__initZ at compile time
called from here: to(& D13TypeInfo_PFZv6__initZ)
called from here: Binds()
Firstly, I don't see why an explicit conversion to string is required (isn't typeid already a string, if not, whats the difference between typeid and typeof?).
Secondly, I can't figure out how to get the explicit function type written out so that it can be executed in main. I can't use F.Type since it is local to the foreach.
You've got a couple problems here, but the main one is that typeid returns an object of type TypeInfo (typeid expression). Fortunately, you can just use F.Type.stringof. Also note that you don't need the mixin to alias Prototype as Type:
void f() { writeln("f"); }
void g() { writeln("g"); }
struct Function(string name, Prototype)
{
const string Name = name;
alias Prototype Type;
}
string Binds(Functions...)()
{
string r;
foreach (F; Functions)
{
// error:
r ~= F.Type.stringof ~ " " ~ F.Name ~ "2 = &" ~ F.Name ~ ";";
}
return r;
}
import std.stdio,
std.conv;
int main()
{
mixin (Binds!(
Function!("f", void function()),
Function!("g", void function())
));
f();
f2();
return 0;
}
Running this prints:
f
f
which I believe is what you're looking for.