Search Results

Search found 763 results on 31 pages for 'casting'.

Page 3/31 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • templates and casting operators

    - by Jonathan Swinney
    This code compiles in CodeGear 2009 and Visual Studio 2010 but not gcc. Why? class Foo { public: operator int() const; template <typename T> T get() const { return this->operator T(); } }; Foo::operator int() const { return 5; } The error message is: test.cpp: In member function `T Foo::get() const': test.cpp:6: error: 'const class Foo' has no member named 'operator T'

    Read the article

  • C++ Class Inheritance architecture - preventing casting

    - by Some One
    I have a structure of base class and a couple of inherited classed. Base class should be pure virtual class, it should prevent instantiation. Inherited classes can be instantiated. Code example below: class BaseClass { public: BaseClass(void); virtual ~BaseClass(void) = 0; }; class InheritedClass : public BaseClass { public: InheritedClass1(void); ~InheritedClass1(void); }; class DifferentInheritedClass : public BaseClass { public: DifferentInheritedClass(void); ~DifferentInheritedClass(void); }; I want to prevent the following operations to happen: InheritedClass *inherited1 = new InheritedClass(); DifferentInheritedClass *inherited2 = new DifferentInheritedClass (); BaseClass *base_1 = inherited1; BaseClass *base_2 = inherited2; *base_1 = *base_2;

    Read the article

  • Typed DefaultListModel to avoid casting

    - by Thomas R.
    Is there a way in java to have a ListModel that only accepts a certain type? What I'm looking for is something like DefaultListModel<String> oder TypedListModel<String>, because the DefaultListModel only implements addElement(Object obj) and get(int index) which returns Object of course. That way I always have to cast from Object to e.g. String and there is no guarantee that there are only strings in my model, even though I'd like to enforce that. Is this a flaw or am I using list models the wrong way?

    Read the article

  • Is this casting safe?

    - by Itsik
    I need to write a Util function (in my c++cli app) that converts a String to a Double or Float or Int. template<typename T> static T MyConvert(String^ str) { return static_cast<T>(System::Convert::ToDouble(str)); } Is this safe? Can it somehow convert 2 to 1.999 and then to 1 if I call MyConvert<int>("2") ? I was wondering why the Convert class isn't templated in the first place? (That would let me call Convert<T> instead of Convert.ToDouble() for all types) This is C++/Cli so I can use any convert methods in c++ or .net, but I only know Convert.ToDouble()|ToString()|ToInt32()) Thanks

    Read the article

  • IGrouping and Casting in Linq

    - by FiveTools
    I have the following query: var groupCats = from g in groups group g by g.Value into grouped select new { GroupCategory = grouped.Key, Categories = GetCategories(grouped.Key, child) }; This works fine. In the anonymous type returned GroupCategory is a string, and Categories are an Enumerable - what is the proper way to declare this instead of using 'var'? I tried: IGrouping<string,string> groupCats = from g in groups group g by g.Value into grouped select new { GroupCategory = grouped.Key, Categories = GetCategories(grouped.Key, child) }; and IGrouping<string,Enumerable<string>> groupCats = from g in groups group g by g.Value into grouped select new { GroupCategory = grouped.Key, Categories = GetCategories(grouped.Key, child) }; In both instances I get: Cannot implicity convert type....An explicit conversion exists (are you missing a cast) How do I cast this?

    Read the article

  • Java: Generics, Class.isaAssignableFrom, and type casting

    - by bguiz
    This method that uses method-level generics, that parses the values from a custom POJO, JXlistOfKeyValuePairs (which is exactly that). The only thing is that both the keys and values in JXlistOfKeyValuePairs are Strings. This method wants to taken in, in addition to the JXlistOfKeyValuePairs instance, a Class<T> that defines which data type to convert the values to (assume that only Boolean, Integer and Float are possible). It then outputs a HashMap with the specified type for the values in its entries. This is the code that I have got, and it is obviously broken. private <T extends Object> Map<String, T> fromListOfKeyValuePairs(JXlistOfKeyValuePairs jxval, Class<T> clasz) { Map<String, T> val = new HashMap<String, T>(); List<Entry> jxents = jxval.getEntry(); T value; String str; for (Entry jxent : jxents) { str = jxent.getValue(); value = null; if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } else if (clasz.isAssignableFrom(Float.class)) { value = (T)(Float.parseFloat(str)); } else { logger.warn("Unsupporteded value type encountered in key-value pairs, continuing anyway: " + clasz.getName()); } val.put(jxent.getKey(), value); } return val; } This is the bit that I want to solve: if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } I get: Inconvertible types required: T found: Boolean Also, if possible, I would like to be able to do this with more elegant code, avoiding Class#isAssignableFrom. Any suggestions? Sample method invocation: Map<String, Boolean> foo = fromListOfKeyValuePairs(bar, Boolean.class);

    Read the article

  • C2664 when casting child class to templated parent class

    - by DC
    I have a parent class which is templated, and a child class which implements it. template< typename T1, typename T2> class ParentClass{ . . . }; class ChildClass : public ParentClass<MyT1, MyT2> { . . . }; And I want to have a pointer which I can use polymorphically: ParentClass<T1, T2>* ptr; ptr = static_cast<ParentClass<MyT1, MyT2>* >(new ChildClass() ); No matter how I cast it, I always get a C2664 which has the same expression: error C2664: cannot convert parameter 1 from 'ParentClass< T1,T2 *' to 'ParentClass< T1,T2 *' Is it not possible to cast pointer types between inherited types if the parent is templated, even if the types specified in the templates are the same?

    Read the article

  • Difference in casting in the following 2 methods

    - by Shrewd Demon
    hi, can somebody please tell me what is the difference between the following two statements, because both of them give me the same results. Also i want to know which is better. Label lblSome = e.Item.FindControl("lblMyLable") as Label; && Label lblSome = (Label)e.Item.FindControl("lblMyLable"); thank you so much.

    Read the article

  • Fun with casting and inheritance

    - by Vaccano
    NOTE: This question is written in a C# like pseudo code, but I am really going to ask which languages have a solution. Please don't get hung up on syntax. Say I have two classes: class AngleLabel: CustomLabel { public bool Bold; // code to allow the label to be on an angle } class Label: CustomLabel { public bool Bold; // Code for a normal label // Maybe has code not in an AngleLabel (align for example). } They both decend from this class: class CustomLabel: Control { protected bool Bold; } The bold field is exposed as public in the descended classes. No interfaces are available on the classes. Now, I have a method that I want to beable to pass in a CustomLabel and set the Bold property. Can this be done without having to 1) find out what the real class of the object is and 2) cast to that object and then 3) make seperate code for each variable of each label type to set bold. Kind of like this: public void SetBold(customLabel: CustomLabel) { AngleLabel angleLabel; NormalLabel normalLabel; if (angleLabel is AngleLabel ) { angleLabel= customLabel as AngleLabel angleLabel.Bold = true; } if (label is Label) { normalLabel = customLabel as Label normalLabel .Bold = true; } } It would be nice to maybe make one cast and and then set bold on one variable. What I was musing about was to make a fourth class that just exposes the bold variable and cast my custom label to that class. Would that work? If so, which languages would it work for? (This example is drawn from an old version of Delphi (Delphi 5)). I don't know if it would work for that language, (I still need to try it out) but I am curious if it would work for C++, C# or Java. If not, any ideas on what would work? (Remember no interfaces are provided and I can not modify the classes.) Any one have a guess?

    Read the article

  • casting between sibling classes, AS3

    - by felix-gasca
    I have two classes, derivedClassA and derivedClassB which both extend parentClass I'm declaring var o:parentClass and then, depending on what's going on, I want to cast o as either being of type derivedClassA or derivedClassB. Essentially, this: var o:parentClass ... if(shouldUseA) o = new derivedClassA(); else o = new derivedClassB(); o.doSomething(); But it's not working, I'm getting all sorts of errors. Isn't this how class inheritance works? I feel like I'm missing something really fundamental, but I can't figure out what. Am I supposed to be using interfaces instead? Is there another way of doing what I want?

    Read the article

  • Casting Type array to Generic array?

    - by George R
    The short version of the question - why can't I do this? I'm restricted to .NET 3.5. T[] genericArray; // Obviously T should be float! genericArray = new T[3]{ 1.0f, 2.0f, 0.0f }; // Can't do this either, why the hell not genericArray = new float[3]{ 1.0f, 2.0f, 0.0f }; Longer version - I'm working with the Unity engine here, although that's not important. What is - I'm trying to throw conversion between its fixed Vector2 (2 floats) and Vector3 (3 floats) and my generic Vector< class. I can't cast types directly to a generic array. using UnityEngine; public struct Vector { private readonly T[] _axes; #region Constructors public Vector(int axisCount) { this._axes = new T[axisCount]; } public Vector(T x, T y) { this._axes = new T[2] { x, y }; } public Vector(T x, T y, T z) { this._axes = new T[3]{x, y, z}; } public Vector(Vector2 vector2) { // This doesn't work this._axes = new T[2] { vector2.x, vector2.y }; } public Vector(Vector3 vector3) { // Nor does this this._axes = new T[3] { vector3.x, vector3.y, vector3.z }; } #endregion #region Properties public T this[int i] { get { return _axes[i]; } set { _axes[i] = value; } } public T X { get { return _axes[0];} set { _axes[0] = value; } } public T Y { get { return _axes[1]; } set { _axes[1] = value; } } public T Z { get { return this._axes.Length (Vector2 vector2) { Vector vector = new Vector(vector2); return vector; } public static explicit operator Vector(Vector3 vector3) { Vector vector = new Vector(vector3); return vector; } #endregion }

    Read the article

  • Casting objects to Integer,string ,...

    - by Milan
    Hello everybody! I have one small problem. I have list of types(int,string,..) ArrayList<Class> typeList; and I have some input values; ArrayList<Object> values; How to cast some value to some type if I know which type from the typeList is the values; typeList.get(i).cast(values.get(i)); <- this is not working??? Actualy I generate dynamic form in runtime. With Java reflection I get parameterTypes from methods from some class, I generate form with input fields and then i want to cast the text from the input fields to specific types from the paramterTypes that I got with Java reflection from some class.

    Read the article

  • Linq-to-XML explicit casting in a generic method

    - by vlad
    I've looked for a similar question, but the only one that was close didn't help me in the end. I have an XML file that looks like this: <Fields> <Field name="abc" value="2011-01-01" /> <Field name="xyz" value="" /> <Field name="tuv" value="123.456" /> </Fields> I'm trying to use Linq-to-XML to get the values from these fields. The values can be of type Decimal, DateTime, String and Int32. I was able to get the fields one by one using a relatively simple query. For example, I'm getting the 'value' from the field with the name 'abc' using the following: private DateTime GetValueFromAttribute(IEnumerable<XElement> fields, String attName) { return (from field in fields where field.Attribute("name").Value == "abc" select (DateTime)field.Attribute("value")).FirstOrDefault() } this is placed in a separate function that simply returns this value, and everything works fine (since I know that there is only one element with the name attribute set to 'abc'). however, since I have to do this for decimals and integers and dates, I was wondering if I can make a generic function that works in all cases. this is where I got stuck. here's what I have so far: private T GetValueFromAttribute<T>(IEnumerable<XElement> fields, String attName) { return (from field in fields where field.Attribute("name").Value == attName select (T)field.Attribute("value").Value).FirstOrDefault(); } this doesn't compile because it doesn't know how to convert from String to T. I tried boxing and unboxing (i.e. select (T) (Object) field.Attribute("value").Value but that throws a runtime Specified cast is not valid exception as it's trying to convert the String to a DateTime, for instance. Is this possible in a generic function? can I put a constraint on the generic function to make it work? or do I have to have separate functions to take advantage of Linq-to-XML's explicit cast operators?

    Read the article

  • C# Type Casting at Runtimefor Array.SetValue

    - by sprocketonline
    I'm trying to create an array using reflection, and insert values into it. I'm trying to do this for many different types so would like a createAndFillArray function capable of this : Type t1 = typeof(A); Type t2 = typeof(B); double exampleA = 22.5; int exampleB = 43; Array arrA = createAndFillArray(t1, exampleA); Array arrB = createAndFillArray(t2, exampleB); private Array createAndFillArray(Type t, object val){ Array arr = Array.CreateInstance( t, 1); //length 1 in this example only, real-world is of variable length. arr.SetValue( val, 0 ); //this causes the following error: "System.InvalidCastException : Object cannot be stored in an array of this type." return arr; } with the class A being as follows: public class A{ public A(){} private double val; public double Value{ get{ return val; } set{ this.val = value; } } public static implicit operator A(double d){ A a = new A(); a.Value = d; return a; } } and class B being very similar, but with int: public class B{ public B(){} private double val; public double Value{ get{ return val; } set{ this.val = value; } } public static implicit operator B(double d){ B b = new B(); b.Value = d; return b; } } I hoped that the implicit operator would have ensured that the double be converted to class A, or the int to class B, and the error avoided; but this is obviously not so. The above is used in a custom deserialization class, which takes data from a custom data format and fills in the corresponding .Net object properties. I'm doing this via reflection and at runtime, so I think both are unavoidable. I'm targeting the C# 2.0 framework. I've dozens, if not hundreds, of classes similar to A and B, so would prefer to find a solution which improved on the createAndFillArray method rather than a solution which altered these classes.

    Read the article

  • C# casting question: from IEnumerable to custom type

    - by Sarah Vessels
    I have a custom class called Rows that implements IEnumerable<Row>. I often use LINQ queries on Rows instances: Rows rows = new Rows { row1, row2, row3 }; IEnumerable<Row> particularRows = rows.Where<Row>(row => condition); What I would like is to be able to do the following: Rows rows = new Rows { row1, row2, row3 }; Rows particularRows = (Rows)rows.Where<Row>(row => condition); However, I get a "System.InvalidCastException: Unable to cast object of type 'WhereEnumerableIterator1[NS.Row]' to type 'NS.Rows'". I do have a Rows constructor taking IEnumerable<Row>, so I could do: Rows rows = new Rows { row1, row2, row3 }; Rows particularRows = new Rows(rows.Where<Row>(row => condition)); This seems bulky, however, and I would love to be able to cast an IEnumerable<Row> to be a Rows since Rows implements IEnumerable<Row>. Any ideas?

    Read the article

  • PHP Casting as Object type in foreach Loop

    - by Coulton
    Within the following code, $quiz_object->personalities contains an array of Personality() objects. // Loop through each personality that exists for the quiz foreach($quiz_object->personalities AS $existing_personality) { // Show all of the existing personalities echo $existing_personality->GetQuizMakerPersonalityHTML(); } How do I "cast" (I think that's the right word) my variable $existing_personality within the foreach loop as the object type? I wish to do this so that when I type $existing_personality->, I get the list of public functions available for that object type. At the moment, Zend doesn't know that it refers to a Personality object within the loop.

    Read the article

  • MySQL Casting in C#

    - by user798080
    Okay, so I'm attempting to print out the contents of a table in a comma-separated file. using (OdbcCommand com = new OdbcCommand("SELECT * FROM pie_data WHERE Pie_ID = ?", con)) { com.Parameters.AddWithValue("", Request.Form["pie_id"]); com.ExecuteNonQuery(); using (OdbcDataReader reader = com.ExecuteReader()) { string finalstring = ""; while (reader.Read()) { finalstring = reader.GetString(9) + ","; for (int i = 0; i <= 8; i = i + 1) { finalstring = finalstring + reader.GetString(i) + ","; } } } Response.Write(finalstring); noredirect = 1; } My table layout is: CREATE TABLE `rent_data` ( `Pies` INT(10) UNSIGNED NOT NULL, `Name` VARCHAR(85) NOT NULL, `Email` VARCHAR(85) NOT NULL, `Pie_Rent` DATE NOT NULL, `Rent_To` DATE NOT NULL, `Returned_Date` DATE NULL DEFAULT NULL, `Place` VARCHAR(100) NOT NULL, `Purpose` MEDIUMTEXT NOT NULL, `Comments` MEDIUMTEXT NULL, `Pie_ID` SMALLINT(5) UNSIGNED ZEROFILL NOT NULL, INDEX `Pie_ID` (`Equipment_ID`) ) The error I'm getting is this: Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Int64' to type 'System.String'. On the line: finalstring = finalstring + reader.GetString(i) + ",";

    Read the article

  • Type-casting. C and C++

    - by thecoshman
    I always though that float var_a = 9.99; int var_b = (int)var_a; was they way to typecast in c++... But here it said that its not the proper C++ way, its the old C way. So I ask, What is the proper C++ way, and more importantly, how do they differ? the C method should still work though shouldn't it.

    Read the article

  • type casting in mysql

    - by muralikalpana
    i have passportno(varchar) in database. i am entering values like this 001,002,003. and i want to display like sorting order. now i wrote query like this "select * from passport_registration where status=1 ORDER BY passportno" then displaying output like this......077,088,099,100,1000,1001,1009,101,1010 i want to diplay sort order. how to do?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >