Questions tagged [static-cast]

A C++ cast operator to convert from one type to another, using only information about the static type of the object being cast

Filter by
Sorted by
Tagged with
13 votes
1 answer
1k views

Will int to double conversion round up, down or to nearest double?

Simple question: Will the conversion from an int, say 100, to a double "round" up or down to the next double or will it always round to the nearest one (smallest delta)? e.g. for static_cast&...
  • 2,911
2 votes
1 answer
47 views

Is there a way to conditionalize a C++ macro against the g++ version to work around this static-cast behavior-change between g++ 9.4.0 and 11.3?

The code below demonstrates that when streaming the return-value from std::stringstream::operator<< to a std::ostream instance, like std::cout, an explicit static_cast (from std::basic_ostream&...
  • 5,085
0 votes
1 answer
113 views

Is there a way for the C++ compiler to warn for unsafe enum class to integer overflow?

There are uses of enum classes in my codebase, where we need to convert to integers for low level functions. There are static casts to uint8_t all over, assuming the enum has a small number of values. ...
1 vote
2 answers
81 views

Is this downcast undefined behaviour?

I am trying to extend std::map's std::pair entries with some extra functionality and want to cast such pairs to a child class of pair. Note that this is the "wrong" direction of polymorphism,...
  • 1,130
1 vote
1 answer
91 views

when does static_cast compile to no CPU instructions

This question is motivated by the following (simplified) example. Consider the following code: void f(unsigned int x) { } int main() { int z = 3; if (z > 0) for (unsigned int i = 0; i &...
  • 6,897
1 vote
1 answer
69 views

Any way to get a warning for static_cast<some_enum_class>(T) where T's type isn't the underlying type of some_enum_class?

I'm reviewing a lot of code where I need to ensure there are no static_cast (or any cast) calls on variables that could be out of range of the enum class that is being cast to. Ideally I'd be able to ...
  • 139
0 votes
1 answer
181 views

Potential null pointer dereference or compiler bug?

I found one more case when compiler thinks that static_cast may return nullptr on non-nullptr argument. It seems that this time there is no undefined behavior, like was before, but maybe I'm missing ...
0 votes
0 answers
79 views

Can static_cast gives nullpt for non-nullptr argument? [duplicate]

The following code gives me a warning "null pointer dereference" despite checking the pointer value before casting: struct ID { virtual ~ID() = default; }; struct IF { virtual void g() = 0; }...
-3 votes
2 answers
114 views

C++ static_cast Incorrect

I am new to C++ and have the following simple code snippet exploring C++ limitations: int main() { float x = 2147483000; int y = static_cast<int>(x); cout << "x: " <&...
  • 57
0 votes
0 answers
63 views

how do I convert a single char to a uint in a well defined way and cross platform way?

Let's say I have a single char: char myChar = 'A'; and I want to populate an uint: uint8_t myUint8 = 0; // 0 is just a default; is it well defined to do this: myUint8 = static_cast<uint8_t>(...
  • 107
0 votes
1 answer
28 views

Wiriting a typecast function for a class which cannot be modified

I have a particular class for which I want to write a typecast operator, but I can't modify the class code directly. Example: class MyClass; // not modifyable class MyClass { // can't do this ...
0 votes
1 answer
58 views

Returning a static cast to a pointer doesn't return a pointer C++

In an "Entity" class, there is a function that takes in a component typename as an argument, and should return a pointer to that component, if found in the component array. Instead it just ...
1 vote
2 answers
36 views

`operator type&` confusion

I have user-defined type: class String::CharProxy { public: const char* operator&() const; char* operator&(); operator char() const; operator char&(); }; The problem is ...
0 votes
0 answers
105 views

static_cast on objects c++ [duplicate]

I am trying to understand why static_cast works different when it is performed on object than when it is performed on a pointer to object. class A { int myA; public: A() { myA = 11; }; ...
  • 73
0 votes
1 answer
168 views

Is there difference between the reinterpret_cast and the static_cast in any pointer-to-pointer conversion?

cppreference/reinterpret_cast conversion/Explanation says Unlike static_cast, but like const_cast, the reinterpret_cast expression does not compile to any CPU instructions (except when converting ...
  • 27
2 votes
1 answer
156 views

Copy const char* to uint8_t array

My C-API takes an array of uint8_t's as config parameter. I'm arriving at its doorsteps with a const char*. How do I now copy the chars over to the uint8_t array in the most unproblematic way? Here's ...
  • 2,911
0 votes
0 answers
17 views

Attach callback function without `std::function` [duplicate]

Issue: I have std::vector<callback_func_t> to store callback. callback_func_t is void(*)(void*) void add_func(callback_func_t fn) is mathod to attach/add callbacks to vector using .push_back ...
1 vote
2 answers
192 views

Why can't I static_cast a void* to a pointer-to-function?

This can be compiled (despite being UB (right?) because fvp == nullptr) int f; void* fvp{}; decltype(f)* fp = static_cast<decltype(f)*>(fvp); but this cannot void f() {} void* fvp{}; decltype(f)...
  • 21.7k
0 votes
0 answers
93 views

How to get rid of these static_casts?

I'm trying to create a C++ class hierarchy of UI "view" classes that wrap platform-specific UI classes. My classes use the pimpl idiom to hide the implementation from the header file. The ...
  • 14.4k
0 votes
0 answers
11 views

Ccan I use operator-overloading for operator >>, so it can be useful while taking inputs in enum?

Can I use the operator-overloading on >>operator instead of static-cast to do input? int input{}; std::cin >> input; // input an integer Pet pet{ static_cast<Pet>(input) }; // ...
0 votes
1 answer
113 views

Why the symbols for cards is not showed ( hearts, spades, diamonds, clubs) when I run the program?

//This program first set 52 cards with their number and their Suit and then it displays them. After that it shuffles the cards and swaps them with random cards and display them. But problem is that ...
0 votes
0 answers
53 views

Is this static_cast safe in different platforms?

Does this cast have defined behavior in different platforms? I want to have the pointer address in 64 bits. if the platform is 32 bits, top bits should be all 0 or 1. This is used for some seed ...
4 votes
1 answer
313 views

Can you static_cast "this" to a derived class in a base class constructor then use the result later?

We ran into this scenario in our codebase at my work, and we had a big debate over whether this is valid C++ or not. Here is the simplest code example I could come up with: template <class T> ...
0 votes
1 answer
43 views

Typecasting from one class to another isnot working

Conversion from SI to ImperialSystem is working but the reverse isnot working. The error message: static_cast: cannot convert from ImperialSystem to SI code: #include<iostream> #define endl '\n' ...
  • 424
0 votes
0 answers
29 views

Static cast with derived keyword (Code understanding) [duplicate]

I was trying to compile c++ code got from internet, unfortunately it is not failed to compile. Since it is heavily templeted code I am struggling to understand and fixing this. The code is giving ...
0 votes
1 answer
151 views

Using a static_cast on non-pointer related types

I discover this compiler trick and I cannot find a name for. Have you any idea? On an Intel processor, I can cast a variable from its base class to an inherited class. It works with MSVC, gcc and ...
  • 13
0 votes
1 answer
83 views

Why does static_cast of an enum class stored in a bit-field change the result?

Given an enum class stored in a bit-field: #include <cstdint> #include <iostream> enum class Orientation: uint8_t { NORMAL = 0, CLOCKWISE = 1, ANTICLOCKWISE = 2 }; ...
  • 135k
0 votes
0 answers
41 views

What does MOZ_ASSERT(static_cast<> == reinterpret_cast<>) do?

I saw a bunch of code in Firefox written like static_cast<>(obj) == reinterpret_cast<>(obj); anyone could help here for why the developers writing so? bool Wrap(JSContext* aCx, mozilla::...
  • 75
0 votes
1 answer
342 views

Can static_cast be used in C source code compiled by C compiler?

I saw C-library with code that compiled by GCC 11 that do static_cast from C code and it perfectly fine for GCC. But when I tried to compile this library in VisualStudio (MSVC) I got error: (this ...
  • 67
1 vote
1 answer
421 views

static_cast() works but static_pointer_cast() does not?

When I write a class like this static_cast() calls the custom conversion operator. But static_pointer_cast() does not compile. Why is that, and what do I need to do to make it work? class A{ //...
  • 555
0 votes
1 answer
157 views

Advantages of static_cast over explicit instantiation/construction?

Considering the following function template func declared within MyClass class template: template < T > class MyClass { public: MyClass() = default; // ... template < typename ...
  • 1,607
0 votes
0 answers
18 views

Cast template class pointer to pointer of a template class within

In short: There's a templatized class object "queue" Another templatized object "task" contains a queue as first member (address of task will point to queue object) An observer ...
  • 2,911
0 votes
1 answer
280 views

Why does this library refrain from using static_cast?

I try to follow the mantra of "no warnings." I try to write my code so that the compiler gives no warnings. I'm starting to use non-standard libraries for the first time. I recently ...
0 votes
1 answer
135 views

Is this a correct way to store different types in the same allocation?

I need to allocate a chunk of memory using malloc and then store multiple values of different plain old data types in there. Is the following a correct way to do it? #include <cstddef> #include &...
2 votes
0 answers
213 views

How to raise error/warning when static_cast-ing values outside the set of enum class

Consider the case where I have to convert an int type to an enum. When doing this with static_cast the risk is that even values out of admissible values of the enum are casted. Take as example the ...
  • 8,062
1 vote
1 answer
128 views

Downcasting pointer to member leads to undefined behavior

I read somewhere that a pointer-to-member of a derived class can be converted to pointer-to-member of its base class. When I have read this, my smart mind started to think of many examples and keep ...
user avatar
2 votes
1 answer
123 views

Does this downcasting lead to undefined behavior?

Given this sample: class Base { public: void foo() {}; }; class Derived : public Base { }; int main() { Base b; Derived* d = static_cast<Derived*>(...
user avatar
2 votes
0 answers
117 views

What's the use of casting a pointer to (Derived*) right before assigning it to a variable of type (Base*)?

What's the use of the static_cast<IDropSource*> in this piece of code (taken from here): HRESULT CDropSource::QueryInterface(REFIID riid, void **ppv){ IUnknown *punk = NULL; if (riid == ...
  • 83
1 vote
1 answer
374 views

argument of type 'unsigned int' is incompatible with parameter of type 'time_t' c++ error

#include <iostream> #include <ctime> #include <cstdlib> #include <time.h> int main() { srand(time(static_cast<unsigned>(0))); std::cout << "Hello ...
  • 11
2 votes
1 answer
99 views

How can the alignment requirement be satisfied?

I think that I am misreading the standard quotation, hence I do not fully understand what's the exact intent of the wording. Firstly, I am already aware of what alignment requirement is, but I can't ...
user avatar
1 vote
1 answer
110 views

Confusion about [expr.static.cast]/13

I can't understand the quote (specifically, the bold part): A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the ...
user avatar
0 votes
2 answers
95 views

Example of useful downcast with static_cast which does not produce undefined behaviour

I am wondering about a short code example of an application of downcast via static_cast, under conditions where there is no undefined behaviour. I have looked around and I found quite a few texts (...
1 vote
1 answer
172 views

Passing 'this' pointer to a static method in a parent class

I am writing an embedded application using freeRTOS and I'm trying to do it in a neat, object-oriented fashion. To start a FreeRTOS task from within an object, you need to give it a static function. ...
user avatar
0 votes
2 answers
86 views

Relying on compiler optimization of multiple static cast calls?

I'm working with a code base where I see the following lines of code auto a = static_cast<custom_type*>(obj.get())->a(); auto b = static_cast<custom_type*>(obj.get())->b(); ...
9 votes
0 answers
221 views

Why (void*)p instead of static_cast<void*>(p) in C++ standard?

ISO/IEC 14882:2020 22.2.1.16 Note 8: The default construct in allocator will call ::new ((void*)p) T(args), but specialized allocators can choose a different definition. Would you be so kind as to ...
3 votes
3 answers
328 views

Why is only static_cast able to return new object of requested type?

Among static_cast, dynamic_cast, reinterpret_cast and const_cast, only static_cast is able to return an object of desirable type, whereas the other type can return only pointer or reference to ...
  • 357
0 votes
0 answers
41 views

What is the right type of C++ cast here? [duplicate]

I like/hate linters so I figured I'd try clang-tidy with all the checks turned on and see how I'm doing and how I can improve. Aside from stylistic or non-applicable rules, I hit this call: ...
  • 2,530
1 vote
1 answer
112 views

Using std::bind with overloaded methods in namespace in C++

#include <iostream> #include <map> #include <functional> namespace xAOD{ namespace EgammaParameters{ enum ShowerShapeType{ var1 = 0, ...
  • 209
0 votes
0 answers
79 views

Static_cast method outside class

I have a CRTP-class, and want to perform intermediate steps with the data passed through the interface. The goal is to be able to call arbitrary method (foo or bar) in the derived class, from B. Edit ...
0 votes
0 answers
63 views

Pass static_casted method as template parameter

I'm trying to generalize the usage of previous-iteration memoization in CRTP-interfaces, where many of the methods refer to derived classes. The CRTP-methods looks like this: inline RetVal method1(...

1
2 3 4 5
11