Search Results

Search found 1346 results on 54 pages for 'ray casting'.

Page 18/54 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Safe to cast pointer to a forward-declared class to its true base class in C++?

    - by Matt DiMeo
    In one header file I have: #include "BaseClass.h" // a forward declaration of DerivedClass, which extends class BaseClass. class DerivedClass ; class Foo { DerivedClass *derived ; void someMethod() { // this is the cast I'm worried about. ((BaseClass*)derived)->baseClassMethod() ; } }; Now, DerivedClass is (in its own header file) derived from BaseClass, but the compiler doesn't know that at the time it's reading the definition above for class Foo. However, Foo refers to DerivedClass pointers and DerivedClass refers to Foo pointers, so they can't both know each other's declaration. First question is whether it's safe (according to C++ spec, not in any given compiler) to cast a derived class pointer to its base class pointer type in the absence of a full definition of the derived class. Second question is whether there's a better approach. I'm aware I could move someMethod()'s body out of the class definition, but in this case it's important that it be inlined (part of an actual, measured hotspot - I'm not guessing).

    Read the article

  • Converting generic type to it's base and vice-versa

    - by Pajci
    Can someone help me with the conversion I am facing in enclosed code ... I commented the lines of code, where I am having problem. Is this even the right way to achieve this ... what I am trying to do, is forward responses of specified type to provided callback. public class MessageBinder { private class Subscriber<T> : IEquatable<Subscriber<T>> where T : Response { ... } private readonly Dictionary<Type, List<Subscriber<Response>>> bindings; public MessageBinder() { this.bindings = new Dictionary<Type, List<Subscriber<Response>>>(); } public void Bind<TResponse>(short shortAddress, Action<ZigbeeAsyncResponse<TResponse>> callback) where TResponse : Response { List<Subscriber<TResponse>> subscribers = this.GetSubscribers<TResponse>(); if (subscribers != null) { subscribers.Add(new Subscriber<TResponse>(shortAddress, callback)); } else { var subscriber = new Subscriber<TResponse>(shortAddress, callback); // ERROR: cannot convert from 'List<Subscriber<TResponse>>' to 'List<Subscriber<Response>>' ... tried LINQ Cast operator - does not work either this.bindings.Add(typeof(TResponse), new List<Subscriber<TResponse>> { subscriber }); } } public void Forward<TResponse>(TResponse response) where TResponse : Response { var subscribers = this.GetSubscribers<TResponse>(); if (subscribers != null) { Subscriber<TResponse> subscriber; Type responseType = typeof (TResponse); if (responseType.IsSubclassOf(typeof (AFResponse))) { // ERROR: Cannot convert type 'TResponse' to 'AFResponse' ... tried cast to object first, works, but is this the right way? var afResponse = (AFResponse)response; subscriber = subscribers.SingleOrDefault(s => s.ShortAddress == afResponse.ShortAddress); } else { subscriber = subscribers.First(); } if (subscriber != null) { subscriber.Forward(response); } } } private List<Subscriber<TResponse>> GetSubscribers<TResponse>() where TResponse : Response { List<Subscriber<Response>> subscribers; this.bindings.TryGetValue(typeof(TResponse), out subscribers); // ERROR: How can I cast List<Subscriber<Response>> to List<Subscriber<TResponse>>? return subscribers; } } Thank you for any help :)

    Read the article

  • Weird exception: Cannot cast String to Boolean when using getBoolean

    - by La bla bla
    I'm getting a very weird error. I have 2 activities. On both I'm getting the SharedPreferences using MODE_PRIVATE (if it matters) by sp = getPreferences(MODE_PRIVATE); on each activity's onCreate() I'm calling sp.getBoolean(IntroActivity.SHOW_INTRO, true) On the IntroActivity this works fine. But when I'm trying in the main activity, I'm getting this 10-12 04:55:23.208: E/AndroidRuntime(11668): FATAL EXCEPTION: main 10-12 04:55:23.208: E/AndroidRuntime(11668): java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.app.SharedPreferencesImpl.getBoolean(SharedPreferencesImpl.java:242) 10-12 04:55:23.208: E/AndroidRuntime(11668): at com.lablabla.parkme.ParkMeActivity$2.onClick(ParkMeActivity.java:194) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.view.View.performClick(View.java:4084) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.view.View$PerformClick.run(View.java:16966) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.os.Handler.handleCallback(Handler.java:615) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.os.Handler.dispatchMessage(Handler.java:92) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.os.Looper.loop(Looper.java:137) 10-12 04:55:23.208: E/AndroidRuntime(11668): at android.app.ActivityThread.main(ActivityThread.java:4745) 10-12 04:55:23.208: E/AndroidRuntime(11668): at java.lang.reflect.Method.invokeNative(Native Method) 10-12 04:55:23.208: E/AndroidRuntime(11668): at java.lang.reflect.Method.invoke(Method.java:511) 10-12 04:55:23.208: E/AndroidRuntime(11668): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 10-12 04:55:23.208: E/AndroidRuntime(11668): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 10-12 04:55:23.208: E/AndroidRuntime(11668): at dalvik.system.NativeStart.main(Native Method) I made sure that I'm not putting a String somewhere in the middle with that same key Any ideas? Thanks! EDIT: some code: //onCreate() sp = getPreferences(MODE_PRIVATE); // other method boolean showIntro = sp.getBoolean(IntroActivity.SHOW_INTRO, true); // Exception is here showIntroCheckBox.setChecked(showIntro); If it matters, the code which throws the exception is inside a button's onClick

    Read the article

  • Creating a function that will handle objects with common properties

    - by geocine
    Take this as an example I have trimmed this example for readability and you may not find the use of this concept here. class Teacher() { public Name {get; set;} public Salt {get; set;} public Department{get; set;} } class Student() { public Name {get; set;} public Salt {get; set;} public Section{get; set;} } public string GetEncryptedName(object Person) { //return encrypted name based on Name and Salt property return encrypt(object.Salt,object.Name) } callig the function GetEncryptedName(Teacher) GetEncryptedName(Student) How do you implement this kind of stuff?

    Read the article

  • Calling Object Methods in Code

    - by Mister R2
    I'm a bit new to PHP, and I'm more experienced with strongly-typed languages such as JAVA, C# or C++.I'm currently writing a web tool in PHP, and I am having an issue trying to do what I want. The simple idea of what I want to do in code is run through some emails I used PHP-IMAP to get. I then create email objects (a class I defined), and put them in an array. Later on the code, however, I cycle through those emails to display them. However, as you might have guessed I'd have an issue with, I try to use an Email Class object method in that later loop -- and I'm pretty sure PHP doesn't know that the variables in the array happen to be Email Class objects! I wrote a toString method, and I want to call it in the loop. While I don't need to do this for the final version of this tool, I would like to find out what I'm missing. This is the class and the loop where I'm calling the method: include 'imap_email_interface.php'; class ImapEmail implements imap_email_interface { // Email data var $msgno; var $to; var $from; var $subject; var $body; var $attachment; // Email behavior /* PHP 4 ~ legacy constructor */ public function ImapEmail($message_number) { $this->__construct(); $this->msgno = $message_number; } /* PHP 5 Constructor */ public function __construct($message_number) { $this->msgno = $message_number; } public function send($send_to) { // Not Yet Needed! Seriously! } public function setHeaderDirectly($TO, $FROM, $SUBJECT) { $this->to = $TO; $this->from = $FROM; $this->subject = $SUBJECT; } public function setHeaderIndirectly($HEADER) { if (isset($HEADER->to[0]->personal)) $this->to = '"'.$HEADER->to[0]->personal.'", '.$HEADER->to[0]->mailbox.'@'.$HEADER->to[0]->host; else $this->to = $HEADER->to[0]->mailbox.'@'.$HEADER->to[0]->host; $this->from = '"'.$HEADER->from[0]->personal.'", '.$HEADER->from[0]->mailbox.'@'.$HEADER->from[0]->host; $this->subject = $HEADER->subject; } public function setBody($BODY) { $this->body = $BODY; } public function setAttachment($ATTCH) { $this->attachment = $ATTCH; } public function toString() { $str = '[TO]: ' . $this->to . '<br />' . '[FROM]: ' . $this->from . '<br />' . '[SUBJECT]: ' . $this->subject . '<br />'; $str .= '[Attachment]: '.$this->attachment.'<br />'; return $str; } } ?> The Loop: foreach ($orderFileEmails as $x) { $x->toString(); echo '<br /><br />'; } Any ideas?

    Read the article

  • C# Bug or Brain Teaser? Cast working only with Coalesce (??) Operator

    - by Alex
    This is very strange, maybe someone can explain what's happening, or this is a bug (though I tend to think that this is probably just something intricate about C#). The following code throws the error "Cannot implicitly convert type 'uint?' to 'uint'.": public void Test(UInt32? p) { UInt32 x = p; } However, this code works without error: public void Test(UInt32? p) { UInt32 x = p ?? 1; } Huh? Why does this work? Why would the coalesce operator cause implicit conversion of UInt32? (nullable) to UInt32 (non-nullable), while the first error message says that there is no implicit conversion between those types?

    Read the article

  • How to solve this Java type safety warning? (Struts2)

    - by Nicolas Raoul
    Map session = ActionContext.getContext().getSession(); session.put("user", user); This code generates a warning: Type safety: The method put(Object, Object) belongs to the raw type Map. References to generic type Map should be parameterized. Map<String, Serializable> session = (Map<String, Serializable>)ActionContext.getContext().getSession(); session.put("user", user); This code generates a warning: Type safety: Unchecked cast from Map to Map. The getSession method belongs to Struts2 so I can't modify it. I would like to avoid using @SuppressWarnings because other warnings can be useful. I guess all Struts2 users in the world faced the same problem... is there an elegant solution?

    Read the article

  • sqrt(int_value + 0.0) ? The point?

    - by Earlz
    Hello, while doing some homework in my very strange C++ book, which I've been told before to throw away, had a very peculiar code segment. I know homework stuff always throws in extra "mystery" to try to confuse you like indenting 2 lines after a single-statement for-loop. But this one I'm confused on because it seems to serve some real-purpose. basically it is like this: int counter=10; ... if(pow(floor(sqrt(counter+0.0)),2) == counter) ... I'm interested in this part especially: sqrt(counter+0.0) Is there some purpose to the +0.0? Is this the poormans way of doing a static cast to a double? Does this avoid some compiler warning on some compiler I do not use? The entire program printed the exact same thing and compiled without warnings on g++ whenever I left out the +0.0 part. Maybe I'm not using a weird enough compiler?

    Read the article

  • Why cast null before checking if object is equal to null?

    - by jacerhea
    I was looking through the "Domain Oriented N-Layered .NET 4.0 Sample App" project and ran across some code that I do not understand. In this project they often use syntax like the following to check arguments for null: public GenericRepository(IQueryableContext context,ITraceManager traceManager) { if (context == (IQueryableContext)null) throw new ArgumentNullException("context", Resources.Messages.exception_ContainerCannotBeNull); Why would you cast null to the type of the object you are checking for null?

    Read the article

  • Bit conversion operations in PHP

    - by Goro
    Hello, I find myself in need of performing bit-level conversion on variables in PHP. In more detail, I have a bit stream that is read as an integer by hardware, and I need to do some operations on the bits to make it into what its actually supposed to be (a float). I have to do this a few times for different formats, and the functionality I need is Being able to select and move individual bits in a variable Being able to cast statically one type of variable to the other (ie. int to float) I know php natively supports bitwise AND, OR, etc, and shift operations, but I was wondering if: there may already be a library in php that does this sort of thing I would be better off with delegating the calculations to some other language Thanks,

    Read the article

  • Is it possible to cast the Elapsed Time function to Integer?

    - by nuvio
    I have the following function: (def elapsedtime (with-out-str (time (run-my-function)))) and I was wondering if is possible to store only the integer value of the time, as I can only store a String at the moment.... Any suggestion? Thanks a lot UPDATE So I did use this: (defmacro nsecs [expr] `(let [start# (. System (nanoTime))] ~expr (- (. System (nanoTime)) start#))) And then modified this: (def elapsedtime (nsecs (run-my-function argument1 argument2))) but doesn't work, what am I doing wrong? "Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Wrong number of args (1) passed to: main$fn--105$nsecs"

    Read the article

  • Changing type of object in a conditional

    - by David Doria
    I'm having a bit of trouble with dynamic_casting. I need to determine at runtime the type of an object. Here is a demo: include include class PersonClass { public: std::string Name; virtual void test(){}; //it is annoying that this has to be here... }; class LawyerClass : public PersonClass { public: void GoToCourt(){}; }; class DoctorClass : public PersonClass { public: void GoToSurgery(){}; }; int main(int argc, char *argv[]) { PersonClass* person = new PersonClass; if(true) { person = dynamic_cast(person); } else { person = dynamic_cast(person); } person-GoToCourt(); return 0; } I would like to do the above. The only legal way I found to do it is to define all of the objects before hand: PersonClass* person = new PersonClass; LawyerClass* lawyer; DoctorClass* doctor; if(true) { lawyer = dynamic_cast(person); } else { doctor = dynamic_cast(person); } if(true) { lawyer-GoToCourt(); } The main problem with this (besides having to define a bunch of objects that won't be use) is that I have to change the name of the 'person' variable. Is there a better way? (I am not allowed to change any of the classes (Person, Lawyer, or Doctor) because they are part of a library that people who will use my code have and won't want to change). Thanks, Dave

    Read the article

  • How to extend WCF returned class properly?

    - by vikasde
    I am using a WCF service in my project. This service returns a class called "Store". I created a new local class which inherits from "Store". My class is called "ExtendedStore". My ExtendedStore looks like this: class ExtendedStore : StoreManagerService.Store { public int Id; .... } Now I am using the WCF service to cast to my class using the following code: StoreManagerService.StoreClient client = new StoreManagerService.StoreClient(); ExtendedStore store = (ExtendedStore) client.GetStore(); // bombs here I am not able to cast the returned Store class from the service to my ExtendedStore class. I get the below error message: Unable to cast object of type 'ConsoleApplication1.StoreManagerService.Store' to type 'ConsoleApplication1.ExtendedStore'. Shouldn't I be able to cast it? If not, is there a workaround?

    Read the article

  • Can 'iterator' type just subclass 'const_iterator'?

    - by doublep
    After another question about iterators I'm having some doubts about custom containers. In my container, iterator is a subclass of const_iterator, so that I get conversion from non-const to const "for free". But is this allowed or are there any drawbacks or non-working scenarios for such a setup?

    Read the article

  • std::bad_cast from parent to child?

    - by polyglot
    For simplicity, class Parent {} class Child1 : Parent {} class Child2 : Parent {} Elsewhere, I created instances of Child1 and Child2 and store it in same vector under Parent: // . . . in .h file, for example vector<Parent> vector_of_parent; // . . . in one particular method Child1 c1(); Child2 c2(); vector_of_parent.push_back(c1); vector_of_parent.push_back(c2); // . . . Then in another method which has access to vector_of_parent, I tried void doSomething(Parent& some_child) { // wrapped in a try block somehow... Child1& c = dynamic_cast<Child1&> some_child; // do something if the cast is successful } void otherMethod() { doSomething(vector_of_parent.at(0)); // vector_of_parent.at(0) is a Child1 } Why is there a std:bad_cast when I call otherMethod()?

    Read the article

  • C++ OOP - Can you 'overload a cast' <- hard to explain in 1 sentence

    - by Brandon Miller
    Well, the WinAPI has a POINT struct, but I am trying to make an alternative class to this so you can set the values of x and y from a constructor. /** * X-Y coordinates */ class Point { public: int X, Y; Point(void) : X(0), Y(0) {} Point(int x, int y) : X(x), Y(y) {} Point(const POINT& pt) : X(pt.x), Y(pt.y) {} Point& operator= (const POINT& other) { X = other.x; Y = other.y; } }; // I have an assignment operator and copy constructor. Point myPtA(3,7); Point myPtB(8,5); POINT pt; pt.x = 9; pt.y = 2; // I can assign a 'POINT' to a 'Point' myPtA = pt; // But I also want to be able to assign a 'Point' to a 'POINT' pt = myPtB; Is it possible to overload operator= in a way so that I can assign a Point to a POINT? Or maybe some other method to achieve this? Thanks in advance.

    Read the article

  • C Typecast: How to

    - by Jean
    #include<stdio.h> int main(void) { unsigned short a,e,f ; // 2 bytes data type unsigned int temp1,temp2,temp4; // 4 bytes data type unsigned long temp3; // 8 bytes data type a=0xFFFF; e=((a*a)+(a*a))/(2*a); // Line 8 //e=(((unsigned long)(a*a)+(unsigned long)(a*a)))/(unsigned int)(2*a); temp1=a*a; temp2=a*a; temp3=(unsigned long)temp1+(unsigned long)temp2; // Line 14 temp4=2*a; f=temp3/temp4; printf("%u,%u,%lu,%u,%u,%u,%u\n",temp1,temp2,temp3,temp4,e,f,a); return(1); } How do I fix the arithmetic (At Line 8 by appropriate typecasting of intermediate results) so that overflows are taken care of ? Currently it prints 65534 instead of expected 65535. Why is the typecast necessary for Line 14 ?

    Read the article

  • Cast base class object to derived class

    - by Popgalop
    Lets say I have two classes, animal and dog like this. class Animal { }; class Dog : public Animal { }; And I have an animal object named animal, that is actually an instance of dog, how would I cast it back to dog? This may seem like an odd question, but I need it because I am writing a programming language interpreter, and on the stack everything is stored as a BaseObject, and all the other datatypes extend BaseObject. How would I cast the base object from the stack, to a specific data type? I have tried something like this Dog dog = static_cast<Dog>(animal); But it gives me an error 1>------ Build started: Project: StackTests, Configuration: Debug Win32 ------ 1> StackTests.cpp 1>c:\users\owner\documents\visual studio 2012\projects\stacktests\stacktests\stacktests.cpp(173): error C2440: 'static_cast' : cannot convert from 'Animal' to 'Dog' 1> No constructor could take the source type, or constructor overload resolution was ambiguous 1>c:\users\owner\documents\visual studio 2012\projects\stacktests\stacktests\stacktests.cpp(173): error C2512: 'Dog' : no appropriate default constructor available ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    Read the article

  • When to use reinterpret_cast?

    - by HeretoLearn
    I am little confused with the applicability of reinterpret_cast vs static_cast. From what I have read the general rules are to use static cast when the types can be interpreted at compile time hence the word static. This is the cast the C++ compiler uses internally for implicit casts also. reinterpret_cast are applicable in two scenarios, convert integer types to pointer types and vice versa or to convert one pointer type to another. The general idea I get is this is unportable and should be avoided. Where I am a little confused is one usage which I need, I am calling C++ from C and the C code needs to hold on to the C++ object so basically it holds a void*. What cast should be used to convert between the void * and the Class type? I have seen usage of both static_cast and reinterpret_cast? Though from what I have been reading it appears static is better as the cast can happen at compile time? Though it says to use reinterpret_cast to convert from one pointer type to another?

    Read the article

  • Hex to bin after logical operations

    - by user355926
    I want: 111 || 100 ---> 111, not 1 100 && 100 ---> 100, not 1 101 && 010 ---> 000, not 0 Broken code #include <stdio.h> main(void){ string hexa = 0xff; strig hexa2 = 0xf1; // CONVERT TO INT??? cast int hexa3 = hexa || hexa2; int hexa4 = hexa && hexa2; puts(hexa3); puts(hexa4); }

    Read the article

  • How to cast a pointer of memory block to std stream

    - by Shahrooz Kia
    I have programed an application on windows XP and in Visual Studio with c++ language. In that app I used LoadResource() API to load a resource for giving a file in the resource memory. It returned a pointer of memory block and I wanna cast the pointer to the std stream to use for compatibility. Could anyone help me?

    Read the article

  • Java Persistence: Cast to something the result of Query.getResultList() ?

    - by GuiSim
    Hey everyone, I'm new to persistence / hibernate and I need your help. Here's the situation. I have a table that contains some stuff. Let's call them Persons. I'd like to get all the entries from the database that are in that table. I have a Person class that is a simple POJO with a property for each column in the table (name, age,..) Here's what I have : Query lQuery = myEntityManager.createQuery("from Person") List<Person> personList = lQuery.getResultList(); However, I get a warning saying that this is an unchecked conversion from List to List<Person> I thought that simply changing the code to Query lQuery = myEntityManager.createQuery("from Person") List<Person> personList = (List<Person>)lQuery.getResultList(); would work.. but it doesn't. Is there a way to do this ? Does persistence allow me to set the return type of the query ? (Through generics maybe ? )

    Read the article

  • C++ conversion operator between types in other libraries

    - by Dave
    For convenience, I'd like to be able to cast between two types defined in other libraries. (Specifically, QString from the Qt library and UnicodeString from the ICU library.) Right now, I have created utility functions in a project namespace: namespace MyProject { const icu_44::UnicodeString ToUnicodeString(const QString& value); const QString ToQString(const icu_44::UnicodeString& value); } That's all well and good, but I'm wondering if there's a more elegant way. Ideally, I'd like to be able to convert between them using a cast operator. I do, however, want to retain the explicit nature of the conversion. An implicit conversion should not be possible. Is there a more elegant way to achieve this without modifying the source code of the libraries? Some operator overload syntax, perhaps?

    Read the article

  • Why does a Linq Cast<T> operation fail when I have an implicit cast defined?

    - by Ryan Versaw
    I've created two classes, with one of them having an implicit cast between them: public class Class1 { public int Test1; } public class Class2 { public int Test2; public static implicit operator Class1(Class2 item) { return new Class1{Test1 = item.Test2}; } } When I create a new list of one type and try to Cast<T> to the other, it fails with an InvalidCastException: List<Class2> items = new List<Class2>{new Class2{Test2 = 9}}; foreach (Class1 item in items.Cast<Class1>()) { Console.WriteLine(item.Test1); } This, however, works fine: foreach (Class1 item in items) { Console.WriteLine(item.Test1); } Why is the implicit cast not called when using Cast<T>?

    Read the article

  • how to cast an array of char into a single integer number?

    - by SepiDev
    Hi guys, i'm trying to read contents of PNG file. As you may know, all data is written in a 4-byte manner in png files, both text and numbers. so if we have number 35234 it is save in this way: [1000][1001][1010][0010]. but sometimes numbers are shorter, so the first bytes are zero, and when I read the array and cast it from char* to integer I get wrong number. for example [0000] [0000] [0001] [1011] sometimes numbers are misinterpreted as negative numbers and simetimes as zero! let me give you an intuitive example: char s_num[4] = {120, 80, 40, 1}; int t_num = 0; t_num = int(s_num); => 3215279148 ?????? the result should be 241 but the output is 3215279148? I wish I could explain my problem well! how can i cast such arrays into a single integer value?

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >