Universal `cast<T>` function

Open
#765 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
25/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
cpp, php
Domain
compilers

Research direction

Start by reading the dependency issue #764 and the existing primitive-cast and instance_cast behavior described here. Determine how compile-time class-string and primitive type strings should be supported by one cast function, then validate the design against the generic array_force use case and its int, float, string, and class-element examples.

Written by the indexing model from the issue text.

Description

Depends on #764.

Problem

Given there are two ways to cast a variable to some type:

  • For primitive types there's (T)$v, where T is a primitive type.
  • For class instances there's instance_cast($o, T::class).

Here we can see that instance-way is fully compatible with generics (you can use class-string type for T::class), but primitives are not, since you can't do ($t)$v (where $t is of type class-string<T>).

Solution

Function cast($v, $t), where $t is known at compile-time and can be

  • Class::class
  • class-string<T>
  • Primitive type string like 'int', 'string', etc.

Use cases

Given mixed[]. Wanted to cast it to int[], float[], string[] or any other more specific type. Currently it's necessary to make own function for each type:

  • array_force_int($array): int[]
  • array_force_float($array): float[]
  • array_force_string($array): string[]
  • ...

All these functions have the same code, only casted type is different:

foreach ($array as $k => $v) {
  $typed_array[$k] = (T)$v; // T is int/float/string/etc.
  // OR
  $typed_array[$k] = instance_cast($v, T); // T is class-string
}

With the cast function it could be just one function array_force($array, $type):

/**
  * @kphp-generic In, Out
  * @param In[] $array
  * @param class-string<Out> $type
  */
function array_force(array $array, $type): array {
  foreach ($array as $k => $v) {
    $typed_array[$k] = cast($v, $type);
  }
}
Dominant language
C++
Stars
1.5k
Forks
116
Avg merge
5d 17h
Merged PRs (30d)
11

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from VKCOM/kphp

All issues in VKCOM/kphp

Similar issues

More C++ issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.