Questions tagged [casting]

Casting is a process where an object type is explicitly converted into another type if the conversion is allowed.

Filter by
Sorted by
Tagged with
29
votes
3answers
67k views

TryCast<T> method

This isn't urgent, it is more along the lines of trivia or a challenge. The solution works fine as it is, but I suspect it could be better. What follows is a method I came up with a while back in a ...
20
votes
5answers
5k views

Count Even Digits In Number

I was asked to complete this CodeStepByStep problem. Here's a quick summary: Write a function named count_even_digits that accepts two integers as parameters ...
19
votes
3answers
7k views

Avoiding code duplication and retaining const correctness

Sometimes I run across the problem of having two member function overloads that only differ in the constness of this (and the return type, but that is less ...
17
votes
2answers
3k views

C++ int_cast<> function for checked casts?

In order to detect run-time integer casting problems, I've created this function*: ...
14
votes
2answers
15k views

C++ string_cast<> template function

In C++, to simplify string conversion between std::string and std::wstring, I created the following utility template functions: ...
11
votes
4answers
12k views

Convert a boxed integer to an nullable integer with potentially different type

Given a boxed integer (with a boxed short, int, ...) I want to convert it to an unboxed, nullable type instead. It should be ...
11
votes
2answers
38k views

How can I avoid unchecked cast warning in my generic recursive Iterator?

It's somewhat odd that Java's collection framework has no iterator for recursive data structures. Since I needed something like this, I wrote my own. First off, I need recursive elements: ...
10
votes
2answers
639 views

Loops for removing unnecessary lines

I have the following method: ...
10
votes
3answers
275 views

Cast inside the method or let the client code cast, which one is better? [closed]

I have two choices of implementing a method, the first one is a generic type where the client code does not have to cast ...
10
votes
1answer
218 views

Here's my interface, so call me …maybe

I'm inspecting VBA code to find obsolete code constructs - namely explicit Call statements, like this: Call DoSomething(42) ...
9
votes
6answers
2k views

Rules engine dynamic type casting

I have a basic switch statement that executes some code on expectedValue and givenValue. The code to execute is guided by the ...
9
votes
5answers
5k views

Python odd number diamond

I worked up a quick diamond program that takes only odd numbers while returning an error with even numbers or 0. The code looks rather ugly to me, especially with the recurring ...
8
votes
3answers
751 views

'StrictInt' Python object class that prohibits casting numbers with non-integer components to `int`

Inspired by and created because of python3 utility: convert safely to int and driven partly by the 'refactor' in my answer. The aforementioned question and my answer drove me to go and do a thing ...
8
votes
1answer
16k views

Workaround for unchecked cast of a deserialized Object to ArrayList<Vehicle>

For a class I was assigned to write code to read objects of the class Vehicle using ObjectInputStream (in). The objects are ...
7
votes
1answer
613 views

Is this a conforming implementation of duration_cast?

Sadly VS2012's duration_cast is broken, and I actually need the functionality which is broken. So, I wrote my own: ...
7
votes
1answer
208 views

An explicit cast for narrowing numeric conversions

Inspired by gsl::narrow_cast, I created my own implementation with the addition of a couple of features: a static assert on the types to ensure the cast is actually narrowing (if future changes to ...
7
votes
1answer
158 views

python3 utility: convert safely to int

I made this utility function to check for parameters. All it does is checking whether a given variable is an int, or a float/str that represent exactly an int (ie. no decimal part or NaN), and casting ...
7
votes
1answer
514 views

Efficient generic type conversion between numeric types in F#

It's easy to write a function that adds two ints in F#: let add x y = x + y Actually, it's the same as: ...
6
votes
3answers
57k views

Cast an object to Decimal? or Int? etc but leave it as null if it is null

In a case like this: object A1 = null; Decimal? B = Convert.ToDecimal(A1); object A2 = null; int? C = Convert.ToInt32(A2); Note that in case where ...
6
votes
3answers
2k views

Converting Array of Floats to UINT8 (`char`) or UINT16 (`unsigned short`) Using SSE4

The problem is given image in 32 Bit Floating Point Format (float) how to convert it to UINT8 (char) or UNIT16 (...
6
votes
1answer
15k views

Cast a raw map to a generic map using a method, cleanly and safely in a fail early manner

Casting, instanceof, and @SuppressWarnings("unchecked") are noisy. It would be nice to stuff them down into a method where they won't need to be looked at. ...
6
votes
2answers
2k views

Converting a region code (short string up to 4 characters) to a 32-bit integer

There is a function that converts region code strings (1 to 4 characters and null terminator) to 32 bit integers codes to be used in maps as keys or values. Blindly casting char* to int* is bad as it ...
6
votes
1answer
705 views

Acyclic Visitor Pattern without dynamic_cast

The goal is to minimize boilerplate code for creating visitors while allowing users to easily define custom visitors without having to add new accept methods for each visitor type. For example, a ...
5
votes
3answers
2k views

Comparing Equals() method from MSDN

I've implemented the Equals() support for my class as follows: ...
5
votes
5answers
15k views

Performance of object-to-string conversion

Using an OR/M I map a lot of rows from database to array of objects (~300k). In these objects some properties are marked with special attribute [Signed]. Row-by-row ...
5
votes
2answers
118 views

Avoiding casts in abstract types

I asked this question on Stack Overflow and in the comments someone had this to say. In a proper design, you should almost never have to do a dynamic_cast, even if it's hidden inside some nice ...
5
votes
1answer
210 views

Changing the type of an object inside a method?

First off, this is not my code. I'm curious what everyone thinks about changing the type of an object inside of a method then modifying the properties of the cast type. I wanted to use composition to ...
5
votes
1answer
391 views

Different Constructors, Same Implementation

I have this class containing two constructors with different signatures but they do the same thing: ...
5
votes
2answers
306 views

add_const or remove_const based on another type

Here is a type trait which - I feel - could fit in std next to std::add_const and ...
5
votes
2answers
65 views

Getting a set of subscribers from a subscriberMap

In my Java event bus project, I have a private generic method that retrieves a Set<Subscriber<E>> from a private ...
5
votes
2answers
1k views

Version of lexical_cast that doesn't use exceptions

I love boost::lexical_cast but its usage of exceptions there is not preferred in most situations I use it. I have implemented a version and it seems to work but I ...
5
votes
1answer
57 views

Add-in for input() with validation

What do you think about this code? Do you have some advices and remarks for me about them? I have started learning python recently. ...
5
votes
1answer
2k views

Normalize integer types to float range

I wrote two template functions to take an integer type and output a float in the given range. One function takes signed integers and the other takes unsigned ...
4
votes
4answers
464 views

Euclidian distance - optimization and casting

I'm trying to optimize a simple Euclidian distance function in C. It's for a DLL, and calculates distances from one point to many. I have: Version 1: ...
4
votes
2answers
2k views

Multiple explicit cast operations

This sample code works fine, but it looks awful. How would you improve this? ...
4
votes
1answer
3k views

Collection of Actions

I am trying to create a class to queue up a series of commands. (Not really a queue as events happen based on time). Each command has a callback (Action) that get's called. However, each Action has a ...
4
votes
2answers
83 views

Setting the positions of nodes based on a layout

I have a bit of code that looks like this: ...
4
votes
1answer
175 views

CRAIICall class

I thought it was a good idea to use this in my C++ projects: ...
4
votes
1answer
183 views

Demonstration of pthread calls

Please review for any unnecessary casting, memory leaks, wrong use of pthread call, or validation problems in the given code. ...
4
votes
2answers
8k views

Is this a proper way to check a viewstate of type int?

In page load I'm saving a query string int value in a viewstate. Then I save it to my DB. Here is the code I use to retrieve viewstate value and validating it: ...
4
votes
3answers
127 views

Associating a string with a derived class

I am using the following code to get a string that is associated with the class of an instance: ...
4
votes
2answers
2k views

Sorting polymorphic classes

I'm learning from "Jumping into C++" by Alex Allain (sample chapter and TOC) and solved the first problem in Chapter 26 "Inheritance and Polymorphism". I'm especially concerned about my use of ...
4
votes
1answer
926 views

A less verbose const_cast

Motivation const_cast is a beast that I seldomly encounter. But when I do so it is mostly a bad experience. Nobody knows what most of the C++ programmers do but ...
4
votes
4answers
603 views

Coding Practice - Float* -> Vector3* cast

If you were given the following: ...
4
votes
2answers
165 views

DB-to-Java value mapper

In my company, I've inherited some Java library that I'm now writing tests to, refactoring and fixing Sonar issues. One particular point that Sonar is complaining about is a big chaining of ...
4
votes
1answer
84 views

Convertible templated math vector

I've made a templated math vector struct with a templated type and templated dimension count. I want my vectors to be convertible so I can easily make, for example, a ...
4
votes
1answer
261 views

strncpy To strcpy Equivalence

I have this ugly function, and I feel that the entire strncpy should just be an strcpy: ...
4
votes
1answer
82 views

Making a Zsync file archive with checksums

I'm learning go by doing it. I tried to port the Java's ZsyncMake implementation into Golang. I also employ the Go's concurrency API with goroutine and channel. I have some experience in Java, but ...
4
votes
1answer
138 views

Test and implementation of a reorderable data structure that stores number of users (classifiable as per gender, country, etc.) of an Application

I have implemented a data structure that allows storage of number of users of a hypothetical application in a tree-like data structure in nodes as per their classification based on categories such as ...
4
votes
0answers
656 views

Implementation of narrow_cast in C++

To summarize what I've been trying to do, I basically tried to make a safe narrow_cast operator, which casts to the Target type if and only if the value is ...