Search Results

Search found 2727 results on 110 pages for 'operator overloading'.

Page 14/110 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • SQL SERVER – Fix: Error: 8117: Operand data type bit is invalid for sum operator

    - by pinaldave
    Here is the very interesting error I received from a reader. He has very interesting question. He attempted to use BIT filed in the SUM aggregation function and he got following error. He went ahead with various different datatype (i.e. INT, TINYINT etc) and he was able to do the SUM but with BIT he faced the problem. Error Received: Msg 8117, Level 16, State 1, Line 1 Operand data type bit is invalid for sum operator. Reproduction of the error: Set up the environment USE tempdb GO -- Preparing Sample Data CREATE TABLE TestTable (ID INT, Flag BIT) GO INSERT INTO TestTable (ID, Flag) SELECT 1, 0 UNION ALL SELECT 2, 1 UNION ALL SELECT 3, 0 UNION ALL SELECT 4, 1 GO SELECT * FROM TestTable GO Following script will work fine: -- This will work fine SELECT SUM(ID) FROM TestTable GO However following generate error: -- This will generate error SELECT SUM(Flag) FROM TestTable GO The workaround is to convert or cast the BIT to INT: -- Workaround of error SELECT SUM(CONVERT(INT, Flag)) FROM TestTable GO Clean up the setup -- Clean up DROP TABLE TestTable GO Workaround: As mentioned in above script the workaround is to covert the bit datatype to another friendly data types like INT, TINYINT etc. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • Implicit conversion while using += operator?

    - by bdhar
    Conside the following code: int main() { signed char a = 10; a += a; // Line 5 a = a + a; return 0; } I am getting this warning at Line 5: d:\codes\operator cast\operator cast\test.cpp(5) : warning C4244: '+=' : conversion from 'int' to 'signed char', possible loss of data Does this mean that += operator makes an implicit cast of the right hand operator to int? P.S: I am using Visual studio 2005

    Read the article

  • Custom types as key for a map - C++

    - by Appu
    I am trying to assign a custom type as a key for std::map. Here is the type which I am using as key. struct Foo { Foo(std::string s) : foo_value(s){} bool operator<(const Foo& foo1) { return foo_value < foo1.foo_value; } bool operator>(const Foo& foo1) { return foo_value > foo1.foo_value; } std::string foo_value; }; When used with std::map, I am getting the following error. error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Foo' (or there is no acceptable conversion) c:\program files\microsoft visual studio 8\vc\include\functional 143 If I change the struct like the below, everything worked. struct Foo { Foo(std::string s) : foo_value(s) {} friend bool operator<(const Foo& foo,const Foo& foo1) { return foo.foo_value < foo1.foo_value; } friend bool operator>(const Foo& foo,const Foo& foo1) { return foo.foo_value > foo1.foo_value; } std::string foo_value; }; Nothing changed except making the operator overloads as friend. I am wondering why my first code is not working? Any thoughts?

    Read the article

  • Is there an "opposite" to the null coalescing operator? (…in any language?)

    - by Jay
    null coalescing translates roughly to return x, unless it is null, in which case return y I often need return null if x is null, otherwise return x.y I can use return x == null ? null : x.y; Not bad, but that null in the middle always bothers me -- it seems superfluous. I'd prefer something like return x :: x.y;, where what follows the :: is evaluated only if what precedes it is not null. I see this as almost an opposite to null coalescence, kind of mixed in with a terse, inline null-check, but I'm [almost] certain that there is no such operator in C#. Are there other languages that have such an operator? If so, what is it called? (I know that I can write a method for it in C#; I use return NullOrValue.of(x, () => x.y);, but if you have anything better, I'd like to see that too.)

    Read the article

  • C++ addition overload ambiguity

    - by Nate
    I am coming up against a vexing conundrum in my code base. I can't quite tell why my code generates this error, but (for example) std::string does not. class String { public: String(const char*str); friend String operator+ ( const String& lval, const char *rval ); friend String operator+ ( const char *lval, const String& rval ); String operator+ ( const String& rval ); }; The implementation of these is easy enough to imagine on your own. My driver program contains the following: String result, lval("left side "), rval("of string"); char lv[] = "right side ", rv[] = "of string"; result = lv + rval; printf(result); result = (lval + rv); printf(result); Which generates the following error in gcc 4.1.2: driver.cpp:25: error: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second: String.h:22: note: candidate 1: String operator+(const String&, const char*) String.h:24: note: candidate 2: String String::operator+(const String&) So far so good, right? Sadly, my String(const char *str) constructor is so handy to have as an implicit constructor, that using the explicit keyword to solve this would just cause a different pile of problems. Moreover... std::string doesn't have to resort to this, and I can't figure out why. For example, in basic_string.h, they are declared as follows: template<typename _CharT, typename _Traits, typename _Alloc> basic_string<_CharT, _Traits, _Alloc> operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs, const basic_string<_CharT, _Traits, _Alloc>& __rhs) template<typename _CharT, typename _Traits, typename _Alloc> basic_string<_CharT,_Traits,_Alloc> operator+(const _CharT* __lhs, const basic_string<_CharT,_Traits,_Alloc>& __rhs); and so on. The basic_string constructor is not declared explicit. How does this not cause the same error I'm getting, and how can I achieve the same behavior??

    Read the article

  • Avoiding new operator in JavaScript -- the better way

    - by greengit
    Warning: This is a long post. Let's keep it simple. I want to avoid having to prefix the new operator every time I call a constructor in JavaScript. This is because I tend to forget it, and my code screws up badly. The simple way around this is this... function Make(x) { if ( !(this instanceof arguments.callee) ) return new arguments.callee(x); // do your stuff... } But, I need this to accept variable no. of arguments, like this... m1 = Make(); m2 = Make(1,2,3); m3 = Make('apple', 'banana'); The first immediate solution seems to be the 'apply' method like this... function Make() { if ( !(this instanceof arguments.callee) ) return new arguments.callee.apply(null, arguments); // do your stuff } This is WRONG however -- the new object is passed to the apply method and NOT to our constructor arguments.callee. Now, I've come up with three solutions. My simple question is: which one seems best. Or, if you have a better method, tell it. First – use eval() to dynamically create JavaScript code that calls the constructor. function Make(/* ... */) { if ( !(this instanceof arguments.callee) ) { // collect all the arguments var arr = []; for ( var i = 0; arguments[i]; i++ ) arr.push( 'arguments[' + i + ']' ); // create code var code = 'new arguments.callee(' + arr.join(',') + ');'; // call it return eval( code ); } // do your stuff with variable arguments... } Second – Every object has __proto__ property which is a 'secret' link to its prototype object. Fortunately this property is writable. function Make(/* ... */) { var obj = {}; // do your stuff on 'obj' just like you'd do on 'this' // use the variable arguments here // now do the __proto__ magic // by 'mutating' obj to make it a different object obj.__proto__ = arguments.callee.prototype; // must return obj return obj; } Third – This is something similar to second solution. function Make(/* ... */) { // we'll set '_construct' outside var obj = new arguments.callee._construct(); // now do your stuff on 'obj' just like you'd do on 'this' // use the variable arguments here // you have to return obj return obj; } // now first set the _construct property to an empty function Make._construct = function() {}; // and then mutate the prototype of _construct Make._construct.prototype = Make.prototype; eval solution seems clumsy and comes with all the problems of "evil eval". __proto__ solution is non-standard and the "Great Browser of mIsERY" doesn't honor it. The third solution seems overly complicated. But with all the above three solutions, we can do something like this, that we can't otherwise... m1 = Make(); m2 = Make(1,2,3); m3 = Make('apple', 'banana'); m1 instanceof Make; // true m2 instanceof Make; // true m3 instanceof Make; // true Make.prototype.fire = function() { // ... }; m1.fire(); m2.fire(); m3.fire(); So effectively the above solutions give us "true" constructors that accept variable no. of arguments and don't require new. What's your take on this. -- UPDATE -- Some have said "just throw an error". My response is: we are doing a heavy app with 10+ constructors and I think it'd be far more wieldy if every constructor could "smartly" handle that mistake without throwing error messages on the console.

    Read the article

  • PostGres Error When Using Distinct : postgres ERROR: could not identify an ordering operator for ty

    - by CaffeineIV
    ** EDIT ** Nevermind, just needed to take out the parens... I get this error: ERROR: could not identify an ordering operator for type record when trying to use DISTINCT Here's the query: select DISTINCT(g.fielda, g.fieldb, r.type) from fields g LEFT JOIN types r ON g.id = r.id; And the errors: ERROR: could not identify an ordering operator for type record HINT: Use an explicit ordering operator or modify the query. ********** Error ********** ERROR: could not identify an ordering operator for type record SQL state: 42883 Hint: Use an explicit ordering operator or modify the query.

    Read the article

  • When should method overloads be refactored?

    - by Ben Heley
    When should code that looks like: DoThing(string foo, string bar); DoThing(string foo, string bar, int baz, bool qux); ... DoThing(string foo, string bar, int baz, bool qux, string more, string andMore); Be refactored into something that can be called like so: var doThing = new DoThing(foo, bar); doThing.more = value; doThing.andMore = otherValue; doThing.Go(); Or should it be refactored into something else entirely? In the particular case that inspired this question, it's a public interface for an XSLT templating DLL where we've had to add various flags (of various types) that can't be embedded into the string XML input.

    Read the article

  • Should we rename overloaded methods?

    - by Mik378
    Assume an interface containing these methods : Car find(long id); List<Car> find(String model); Is it better to rename them like this? Car findById(long id); List findByModel(String model); Indeed, any developer who use this API won't need to look at the interface for knowing possible arguments of initial find() methods. So my question is more general : What is the benefit of using overloaded methods in code since it reduce readability?

    Read the article

  • Recognizing when to use the mod operator

    - by Will
    I have a quick question about the mod operator. I know what it does; it calculates the remainder of a division. My question is, how can I identify a situation where I would need to use the mod operator? I know I can use the mod operator to see whether a number is even or odd and prime or composite, but that's about it. I don't often think in terms of remainders. I'm sure the mod operator is useful and I would like to learn to take advantage of it. I just have problems identifying where the mod operator is applicable. In various programming situations, it is difficult for me to see a problem and realize "hey! the remainder of division would work here!" Any tips or strategies? Thanks

    Read the article

  • Is there an exponent operator in C#?

    - by Charlie
    For example, does an operator exist to handle this? float Result, Number1, Number2; Number1 = 2; Number2 = 2; Result = Number1 (operator) Number2; In the past the ^ operator has served as an exponential operator in other languages, but in C# it is a bit-wise operator. Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?

    Read the article

  • How to prevent duplicate data access methods that retrieve similar data?

    - by Ronald Wildenberg
    In almost every project I work on with a team, the same problem seems to creep in. Someone writes UI code that needs data and writes a data access method: AssetDto GetAssetById(int assetId) A week later someone else is working on another part of the application and also needs an AssetDto but now including 'approvers' and writes the following: AssetDto GetAssetWithApproversById(int assetId) A month later someone needs an asset but now including the 'questions' (or the 'owners' or the 'running requests', etc): AssetDto GetAssetWithQuestionsById(int assetId) AssetDto GetAssetWithOwnersById(int assetId) AssetDto GetAssetWithRunningRequestsById(int assetId) And it gets even worse when methods like GetAssetWithOwnerAndQuestionsById start to appear. You see the pattern that emerges: an object is attached to a large object graph and you need different parts of this graph in different locations. Of course, I'd like to prevent having a large number of methods that do almost the same. Is it simply a matter of team discipline or is there some pattern I can use to prevent this? In some cases it might make sense to have separate methods, i.e. getting an asset with running requests may be expensive so I do not want to include these all the time. How to handle such cases?

    Read the article

  • Trying to reduce the speed overhead of an almost-but-not-quite-int number class

    - by Fumiyo Eda
    I have implemented a C++ class which behaves very similarly to the standard int type. The difference is that it has an additional concept of "epsilon" which represents some tiny value that is much less than 1, but greater than 0. One way to think of it is as a very wide fixed point number with 32 MSBs (the integer parts), 32 LSBs (the epsilon parts) and a huge sea of zeros in between. The following class works, but introduces a ~2x speed penalty in the overall program. (The program includes code that has nothing to do with this class, so the actual speed penalty of this class is probably much greater than 2x.) I can't paste the code that is using this class, but I can say the following: +, -, +=, <, > and >= are the only heavily used operators. Use of setEpsilon() and getInt() is extremely rare. * is also rare, and does not even need to consider the epsilon values at all. Here is the class: #include <limits> struct int32Uepsilon { typedef int32Uepsilon Self; int32Uepsilon () { _value = 0; _eps = 0; } int32Uepsilon (const int &i) { _value = i; _eps = 0; } void setEpsilon() { _eps = 1; } Self operator+(const Self &rhs) const { Self result = *this; result._value += rhs._value; result._eps += rhs._eps; return result; } Self operator-(const Self &rhs) const { Self result = *this; result._value -= rhs._value; result._eps -= rhs._eps; return result; } Self operator-( ) const { Self result = *this; result._value = -result._value; result._eps = -result._eps; return result; } Self operator*(const Self &rhs) const { return this->getInt() * rhs.getInt(); } // XXX: discards epsilon bool operator<(const Self &rhs) const { return (_value < rhs._value) || (_value == rhs._value && _eps < rhs._eps); } bool operator>(const Self &rhs) const { return (_value > rhs._value) || (_value == rhs._value && _eps > rhs._eps); } bool operator>=(const Self &rhs) const { return (_value >= rhs._value) || (_value == rhs._value && _eps >= rhs._eps); } Self &operator+=(const Self &rhs) { this->_value += rhs._value; this->_eps += rhs._eps; return *this; } Self &operator-=(const Self &rhs) { this->_value -= rhs._value; this->_eps -= rhs._eps; return *this; } int getInt() const { return(_value); } private: int _value; int _eps; }; namespace std { template<> struct numeric_limits<int32Uepsilon> { static const bool is_signed = true; static int max() { return 2147483647; } } }; The code above works, but it is quite slow. Does anyone have any ideas on how to improve performance? There are a few hints/details I can give that might be helpful: 32 bits are definitely insufficient to hold both _value and _eps. In practice, up to 24 ~ 28 bits of _value are used and up to 20 bits of _eps are used. I could not measure a significant performance difference between using int32_t and int64_t, so memory overhead itself is probably not the problem here. Saturating addition/subtraction on _eps would be cool, but isn't really necessary. Note that the signs of _value and _eps are not necessarily the same! This broke my first attempt at speeding this class up. Inline assembly is no problem, so long as it works with GCC on a Core i7 system running Linux!

    Read the article

  • Consistency in placing operator functions

    - by wrongusername
    I have a class like this: class A { ...private functions, variables, etc... public: ...some public functions and variables... A operator * (double); A operator / (double); A operator * (A); ...and lots of other operators } However, I want to also be able to do stuff like 2 * A instead of only being allowed to do A * 2, and so I would need functions like these outside of the class: A operator * (double, A); A operator / (double, A); ...etc... Should I put all these operators outside of the class for consistency, or should I keep half inside and half outside?

    Read the article

  • Implementing a non-public assignment operator with a public named method?

    - by Casey
    It is supposed to copy an AnimatedSprite. I'm having second thoughts that it has the unfortunate side effect of changing the *this object. How would I implement this feature without the side effect? EDIT: Based on new answers, the question should really be: How do I implement a non-public assignment operator with a public named method without side effects? (Changed title as such). public: AnimatedSprite& AnimatedSprite::Clone(const AnimatedSprite& animatedSprite) { return (*this = animatedSprite); } protected: AnimatedSprite& AnimatedSprite::operator=(const AnimatedSprite& rhs) { if(this == &rhs) return *this; destroy_bitmap(this->_frameImage); this->_frameImage = create_bitmap(rhs._frameImage->w, rhs._frameImage->h); clear_bitmap(this->_frameImage); this->_frameDimensions = rhs._frameDimensions; this->CalcCenterFrame(); this->_frameRate = rhs._frameRate; if(rhs._animation != nullptr) { delete this->_animation; this->_animation = new a2de::AnimationHandler(*rhs._animation); } else { delete this->_animation; this->_animation = nullptr; } return *this; }

    Read the article

  • What's the false operator in C# good for?

    - by Jakub Šturc
    There are two weird operators in C#: the true operator the false operator If I understand this right these operators can be used in types which I want to use instead of a boolean expression and where I don't want to provide an implicit conversion to bool. Let's say I have a following class: public class MyType { public readonly int Value; public MyType(int value) { Value = value; } public static bool operator true (MyType mt) { return mt.Value > 0; } public static bool operator false (MyType mt) { return mt.Value < 0; } } So I can write the following code: MyType mTrue = new MyType(100); MyType mFalse = new MyType(-100); MyType mDontKnow = new MyType(0); if (mTrue) { // Do something. } while (mFalse) { // Do something else. } do { // Another code comes here. } while (mDontKnow) However for all the examples above only the true operator is executed. So what's the false operator in C# good for? Note: More examples can be found here, here and here.

    Read the article

  • Why do not C++11's move constructor/assignment operator act as expected

    - by xmllmx
    #include <iostream> using namespace std; struct A { A() { cout << "A()" << endl; } ~A() { cout << "~A()" << endl; } A(A&&) { cout << "A(A&&)" << endl; } A& operator =(A&&) { cout << "A& operator =(A&&)" << endl; return *this; } }; struct B { // According to the C++11, the move ctor/assignment operator // should be implicitly declared and defined. The move ctor // /assignment operator should implicitly call class A's move // ctor/assignment operator to move member a. A a; }; B f() { B b; // The compiler knows b is a temporary object, so implicitly // defined move ctor/assignment operator of class B should be // called here. Which will cause A's move ctor is called. return b; } int main() { f(); return 0; } My expected output should be: A() A(A&&) ~A() ~A() However, the actual output is: (The C++ compiler is: Visual Studio 2012) A() ~A() ~A() Is this a bug of VC++? or just my misunderstanding?

    Read the article

  • C++ operator lookup rules / Koenig lookup

    - by John Bartholomew
    While writing a test suite, I needed to provide an implementation of operator<<(std::ostream&... for Boost unit test to use. This worked: namespace theseus { namespace core { std::ostream& operator<<(std::ostream& ss, const PixelRGB& p) { return (ss << "PixelRGB(" << (int)p.r << "," << (int)p.g << "," << (int)p.b << ")"); } }} This didn't: std::ostream& operator<<(std::ostream& ss, const theseus::core::PixelRGB& p) { return (ss << "PixelRGB(" << (int)p.r << "," << (int)p.g << "," << (int)p.b << ")"); } Apparently, the second wasn't included in the candidate matches when g++ tried to resolve the use of the operator. Why (what rule causes this)? The code calling operator<< is deep within the Boost unit test framework, but here's the test code: BOOST_AUTO_TEST_SUITE(core_image) BOOST_AUTO_TEST_CASE(test_output) { using namespace theseus::core; BOOST_TEST_MESSAGE(PixelRGB(5,5,5)); // only compiles with operator<< definition inside theseus::core std::cout << PixelRGB(5,5,5) << "\n"; // works with either definition BOOST_CHECK(true); // prevent no-assertion error } BOOST_AUTO_TEST_SUITE_END() For reference, I'm using g++ 4.4 (though for the moment I'm assuming this behaviour is standards-conformant).

    Read the article

  • On C++ global operator new: why it can be replaced

    - by Jimmy
    I wrote a small program in VS2005 to test whether C++ global operator new can be overloaded. It can. #include "stdafx.h" #include "iostream" #include "iomanip" #include "string" #include "new" using namespace std; class C { public: C() { cout<<"CTOR"<<endl; } }; void * operator new(size_t size) { cout<<"my overload of global plain old new"<<endl; // try to allocate size bytes void *p = malloc(size); return (p); } int main() { C* pc1 = new C; cin.get(); return 0; } In the above, my definition of operator new is called. If I remove that function from the code, then operator new in C:\Program Files (x86)\Microsoft Visual Studio 8\VC\crt\src\new.cpp gets called. All is good. However, in my opinion, my implementations of operator new does NOT overload the new in new.cpp, it CONFLICTS with it and violates the one-definition rule. Why doesn't the compiler complain about it? Or does the standard say since operator new is so special, one-definition rule does not apply here? Thanks.

    Read the article

  • Operator+ for a subtype of a template class.

    - by baol
    I have a template class that defines a subtype. I'm trying to define the binary operator+ as a template function, but the compiler cannot resolve the template version of the operator+. #include <iostream> template<typename other_type> struct c { c(other_type v) : cs(v) {} struct subtype { subtype(other_type v) : val(v) {} other_type val; } cs; }; template<typename other_type> typename c<other_type>::subtype operator+(const typename c<other_type>::subtype& left, const typename c<other_type>::subtype& right) { return typename c<other_type>::subtype(left.val + right.val); } // This one works // c<int>::subtype operator+(const c<int>::subtype& left, // const c<int>::subtype& right) // { return c<int>::subtype(left.val + right.val); } int main() { c<int> c1 = 1; c<int> c2 = 2; c<int>::subtype cs3 = c1.cs + c2.cs; std::cerr << cs3.val << std::endl; } I think the reason is because the compiler (g++4.3) cannot guess the template type so it's searching for operator+<int> instead of operator+. What's the reason for that? What elegant solution can you suggest?

    Read the article

  • Operator+ for a subtype of a template classe.

    - by baol
    I have a template class that defines a subtype. I'm trying to define the binary operator+ as a template function, but the compiler cannot resolve the template version of the operator+. #include <iostream> template<typename other_type> struct c { c(other_type v) : cs(v) {} struct subtype { subtype(other_type v) : val(v) {} other_type val; } cs; }; template<typename other_type> typename c<other_type>::subtype operator+(const typename c<other_type>::subtype& left, const typename c<other_type>::subtype& right) { return typename c<other_type>::subtype(left.val + right.val); } // This one works // c<a>::subtype operator+(const c<a>::subtype& left, // const c<a>::subtype& right) // { return c<a>::subtype(left.val + right.val); } int main() { c<int> c1 = 1; c<int> c2 = 2; c<int>::subtype cs3 = c1.cs + c2.cs; std::cerr << cs3.val << std::endl; } I think the reason is because the compiler (g++4.3) cannot guess the template type so it's searching for operator+<int> instead of operator+. What's the reason for that? What elegant solution can you suggest?

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >