nim-lang / RFCs

A repository for your Nim proposals.
136 stars 23 forks source link

[C++] Constructors as default initializers #532

Closed jmgomez closed 1 year ago

jmgomez commented 1 year ago

Abstract

This RFC pretends to expand constructors so they can be (re)used as default initializers.

Motivation

No response

Description

From the manual:

“The constructor pragma can be used in two ways: in conjunction with importcpp to import a C++ constructor, and to declare constructors that operate similarly to virtual.

It forward declares the constructor in the type definition. When the constructor has parameters, it also generates a default constructor. Notice, inside the body of the constructor one has access to this which is of the type ptr Foo. No result variable is available.”

When a type contains an importcpp type, the initializer {} is produced. This RFC goal is to replace that initializer with an explicit constructor call if one is defined. This will allow the user to skip the default constructor call which can be deleted causing multiple issues (https://github.com/nim-lang/Nim/issues/22633)

The way a user would mark how a initializer is defined is by filling default params on a constructor proc. Default constructor (no params) won't be considered. For instance consider:

{.emit:"""/*TYPESECTION*/
struct CppClass {
  int x;
  CppClass(int x): x(x) {}
};
""".}

type
  CppClass {.importcpp.} = object
    x: cint

proc makeCppClass(x: cint = 10): CppClass {.importcpp: "CppClass(@)", constructor.}

makeCppClass as is marked as constructor and has all is params filled will be a candidate. The compiler will use it and produce CppClass myVar = {10} instead of CppClass myVar = {}. When there are multiple candidate that matches, the first one will be picked.

The implementations wont require any new pragma or significant changes into the compiler as it will reuse both, the constructor and the memberProcsPerTypelist already existing in the module graph (probably it will be refactor though).

Code Examples

No response

Backwards Compatibility

No response

jmgomez commented 1 year ago

Implemented by https://github.com/nim-lang/Nim/pull/22694