problem about implicit-conversion-Collection of common programming errors
BoltClock
c# .net nullable implicit-conversion
I encountered some interesting behavior in the interaction between Nullable and implicit conversions. I found that providing an implicit conversion for a reference type from a value type it permits the Nullable type to be passed to a function requiring the reference type when I instead expect a compilation error. The below code demonstrates this:static void Main(string[] args) {PrintCatAge(new Cat(13));PrintCatAge(12);int? cat = null;PrintCatAge(cat); }private static void PrintCatAge(Cat cat) {i
default.kramer
c# generics implicit-conversion
Given these types:class A { } class B {public static implicit operator A(B me){return new A();} }class Test<T> where T : A { }I triedvar b = new Test<B>();And expected it to fail, which it did. But the error message isThe type ‘B’ cannot be used as type parameter ‘T’ in the generic type or method ‘Test’. There is no implicit reference conversion from ‘B’ to ‘A’.But there is an implicit reference conversion from B to A. Is this just a strange message? There is not an implicit referenc
sll
c# .net json implicit-conversion
I have the following business objects:public abstract class Product{public int Id { get; set; }public bool OnStock { get; set; }}public class ProductForImport : Product{public int ImportId { get; set; }}public class ProductForExport : Product{public int ExportId { get; set; }public bool IsExportable { get; set; }public bool IsUsable { get; set; }public string OtherParam {get; set;}public static implicit operator ProductForExport(ProductForImport pfi){ProductForExport p = new ProductForExport();p
Nordlöw
c++ stl containers implicit-conversion stdstring
Why doesn’t C++ have implicit conversion to bool defined for std::string and STL containers when writing code likeif (!x.empty()) { … }instead of more shorterif (x) { … }when x is of type std::string or for example std::vector?I’m also puzzled by the fact that std::string (in C++03) doesn’t implicit convert to const char* in STL examples likestd::string s(“filename”); std::ofstream(s.c_str();
Pete Fordham
c++ c++11 casting variadic-templates implicit-conversion
Given this code:#include <iostream>template<typename… Args> class X;template<typename T> class X<T> {public:T value;X(T value_) : value(value_) {} };template<typename T, typename… Args> class X<T, Args…> : public X<Args…> {public:T value;X(T value_, Args… args) : value(value_), X<Args…>(args…) {} };template<typename T> std::ostream& operator <<(std::ostream& stream, const X<T>& value_) {stream << va
masterchris_99
c# .net generics properties implicit-conversion
I want to use the generic class with implicit operators. The problem is to use underlaying functions. I think the best describtion is my codepublic class AnnotationField<T> {public T Value { get; set; }public bool IsNullValue { get; set; }public CompareTypes CompareType { get; set; }public static implicit operator T(AnnotationField<T> temp){return temp.Value;}public static implicit operator AnnotationField<T>(T temp){Type correctType = Nullable.GetUnderlyingType(typeof(T)) ?? t
Philipp Eger
java casting implicit-conversion
I’ve got an excercise from university which looks like:int a = 10; int b = 3;double c = a / b;The question is: Which value is c.Now I would say, c is 3.3. It’s casted implicit to double before calculating the result. But the correct answer to this question is according to my records 3.0. How this can be? Does the compiler really calculate the result first as integer and then in a second step casts it to double?Or did I understand that incorrectly?
RAbraham
scala design implicit-conversion implicit
I have a question on type design. Why does Int not extend the Ordered trait. Isn’t Int ordered by nature?Instead, the scala library provides implicit ‘orderer’ methods which convert Int to Ordered[Int]. What are the design choices being made here?Example taken from the book Programming in Scaladef maxListImpParm[T <% Ordered[T]](elements:List[T]):T= …maxListImpParm(List(1,5,10,3)) // works because of implicit methods
aspiring
c# operators implicit-conversion
I was reading atomsite code, i found this:public static implicit operator XElement(XmlBase xmlBase){return xmlBase.Xml;}what that means?
Erwin Mayer
c# visual-studio-2010 ide implicit-conversion
Implicit conversions when using DateTime/DateTimeOffset, or int/decimal variables can cause unexpected behaviors at runtime, so I would prefer to raise warning or errors at compile time when such a conversion is detected.How can I achieve that in Visual Studio 2010?
user1151923
c# string int implicit-conversion
For example, an int with a value of 10 would always be converted to “10”, no? Is it not possible to define such conversion yourself?EDIT: what I’m asking for is:int i = 10; Blah(i);public void Blah(string param) { … }
Chris Boden
c# implicit-conversion
I’m currently working on an application where I need to load data from an SQL database and then assign the retrieved values into the properties of an object. I’m doing this by using reflection since the property names and column names are the same. However, many of the properties are using a custom struct type that is basically a currency wrapper for the decimal type. I have defined an implicit conversion in my struct:public static implicit operator Currency(decimal d) {return new Currency(d); }
mark
c++ gcc implicit-conversion
Give the following function:osal_allocator* SharedMemoryManager::allocator();I Where osal_allocator is a ‘c’ structure, containing function pointers.And the a wrapper class that provides the following constructor:Allocator::Allocator( osal_allocator* );A function makes the following call:001 SomeFunc( SharedMemoryManager* shm ) 002 { 003 Allocator myAllocator = shm.allocator(); 004 005 myAllocator.doSomething(); 006 007 // stuff 008 }The code fails with a SIG SEGV. The reason is that
Timwi
c# implicit-conversion
Consider the following code:class Program {public static explicit operator long(Program x) { return 47; }static int Main(string[] args){var x = new Program();Console.WriteLine((decimal) x);} }To my surprise, this outputs 47; in other words, the explicit operator long is called even though the cast is to decimal.Is there something in the C# spec that explicitly says that this should happen (if so, where exactly) or is this the result of some other rule(s) I’m missing?
curiousguy
c++ implicit-conversion lvalue rvalue lvalue-to-rvalue
C++ Standard (4/5) the lvalue-to-rvalue conversion is not done on theoperand of the unary & operator.For example:int x; int *p = &x;In the above case, are p are &x both lvalues? or What would be an appropriate example?Edit:What about this?int &r = x;I’m sure there will be no conversion in this statement, but i’m confused how does & operator involve in this?
Nawaz
c++ stream c++11 implicit-conversion
Will the following give a compilation error?delete cout; delete cin;The answer is : No. It is a flaw in the implementation of stream classes from the Standard library. They have the following conversion function to void* type, which means, all stream objects can be implicitly converted to void*:operator void * ( ) const;This is very useful in general as it lets us write very idiomatic loop, say, when reading input from files. But at the same time, it lets user to write delete stream. As I said
user2337207
c++ c++11 constructor standards implicit-conversion
What are the specific problems that are being avoided with the restrictions imposed by this clause 12.7p3 (see the first part of paragraph below)? In the example shown in 12.7p3 (see below) why X(this) is considered defined? Is it because X is not in the path E C D B A ?struct A { }; struct B : virtual A { }; struct C : B { }; struct D : virtual A { D(A*); }; struct X { X(A*); }; struct E : C, D, X { E() : D(this), // undefined: upcast from E* to A*// might use path E* – D* – A*// but D is not
noobcoder
c casting printf implicit-conversion format-specifiers
I have a given code, in my opinion there is something wrong with that code: I compile under XINU.The next variables are relevant :unsigned long ularray[]; int num; char str[100];There is a function returns int:int func(int i) {return ularray[i]; }now the code is like this:num = func(i); sprintf(str, “number = %lu\n”, num); printf(str);The problem is I get big numbers while printing with %lu, which is not correct.If i change the %lu to %d, i get the correct number. For example: with %lu i get 276
Yi Jiang
javascript implicit-conversion comparison-operators
The code:var num = 20;if(num == “20”) {alert(“It works”); } else {alert(“Not working”); }The question:In C programming we have a rule name data type promotion, where when there’s a mix of data type (example: addition of integer and floating point), the integer will first converted to floating point before the addition is being carry out. The code above will prompt me an alert box with the message “It works” that shows the if test condition is evaluate to true. For loosely typed JavaScript, I’m j
Max Ehrlich
c# c#-4.0 generics ienumerable implicit-conversion
I have a class that is used to hold values loaded from a configuration file. To make this class easier to use, I have set up many implicit conversions to some basic types. One of the types I would like to convert to is IEnumerable(T). For example, if the programmer has a value like this in the config filea = “1,2,3,4”In C# code, he can writeIEnumerable<int> a = Config.a;Ideally what I would like to write is thispublic static implicit operator IEnumerable<T>(ConfigurationValue val){st
Hossein
c++ constructor operator-overloading implicit-conversion access-specifier
Scott Meyers in his book “Effective C++” says,To disallow functionality automatically provided by compilers, declarethe corresponding member functions private and give noimplementations.Then if somebody inadvertently calls one, they willget an error at link-time.I tried to write a sample program for achieving what Scott was trying to explain. I could achieve the same even when the member function was declared public and given no implementation. The link-error occurred in my case also when i trie
xmllmx
c++ c type-conversion implicit-conversion string-literals
This question already has an answer here:Why is passing a string literal into a char* argument only sometimes a compiler error?6 answersvoid f(char* p) {}int main() {f(“Hello”); // OKauto p = “Hello”;f(p); // error C2664: ‘void f(char *)’ : cannot convert parameter 1 // from ‘const char *’ to ‘char *’ } The code was compiled with VC++ Nov 2012 CTP.§2.14.15 String Literals, Section 7A narrow string literal has type “array of n const char”, where n isthe size of the string as defined below, and ha
Dan
c implicit-conversion
What’s going on here:printf(“result = %d\n”, 1); printf(“result = %f\n”, 1);outputs:result = 1 result = 0.000000If I ensure the type of these variables before trying to print them, it works fine of course. Why is the second print statement not getting implicitly converted to 1.00000?
Lightness Races in Orbit
c++ visual-c++ clang implicit-conversion overload-resolution
This example seems to compile with VC10 and gcc (though my version of gcc is very old).EDIT: R. Martinho Fernandez tried this on gcc 4.7 and the behaviour is still the same.struct Base {operator double() const { return 0.0; } };struct foo {foo(const char* c) {} };struct Something : public Base {void operator[](const foo& f) {} };int main() {Something d;d[“32”];return 0; }But clang complains:test4.cpp:19:6: error: use of overloaded operator ‘[]’ is ambiguous (with operand types ‘Something’ an
Jean-Philippe Pellet
scala macros literals implicit-conversion
In my app, I am keeping track of the number of credits the user has. To add some type checking, I’m using a Credits class similar to this one:case class Credits(val numCredits: Int) extends Ordered[Credits] {… }Suppose I have a function def accept(creds: Credits): Unit that I want to call. Would there be a way for me to call it withprocess(Credits(100)) process(0)but not with this?process(10)I.e., I’d like to provide an implicit conversion only from the literal 0 and none other. Right now, I j
Web site is in building