Search Results

Search found 2498 results on 100 pages for 'unary operator'.

Page 11/100 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Where to add an overloaded operator for the tr1::array?

    - by phlipsy
    Since I need to add an operator& for the std::tr1::array<bool, N> I wrote the following lines template<std::size_t N> std::tr1::array<bool, N> operator& (const std::tr1::array<bool, N>& a, const std::tr1::array<bool, N>& b) { std::tr1::array<bool, N> result; std::transform(a.begin(), a.end(), b.begin(), result.begin(), std::logical_and<bool>()); return result; } Now I don't know in which namespace I've to put this function. I considered the std namespace as a restricted area. Only total specialization and overloaded function templates are allowed to be added by the user. Putting it into the global namespace isn't "allowed" either in order to prevent pollution of the global namespace and clashes with other declarations. And finally putting this function into the namespace of the project doesn't work since the compiler won't find it there. What had I best do? I don't want to write a new array class putted into the project namespace. Because in this case the compiler would find the right namespace via argument dependent name lookup. Or is this the only possible way because writing a new operator for existing classes means extending their interfaces and this isn't allowed either for standard classes?

    Read the article

  • Operator overloading in generic struct: can I create overloads for specific kinds(?) of generic?

    - by Carson Myers
    I'm defining physical units in C#, using generic structs, and it was going okay until I got the error: One of the parameters of a binary operator must be the containing type when trying to overload the mathematical operators so that they convert between different units. So, I have something like this: public interface ScalarUnit { } public class Duration : ScalarUnit { } public struct Scalar<T> where T : ScalarUnit { public readonly double Value; public Scalar(double Value) { this.Value = Value; } public static implicit operator double(Scalar<T> Value) { return Value.Value; } } public interface VectorUnit { } public class Displacement : VectorUnit { } public class Velocity : VectorUnit { } public struct Vector<T> where T : VectorUnit { #... public static Vector<Velocity> operator /(Vector<Displacement> v1, Scalar<Duration> v2) { return new Vector<Velocity>(v1.Magnitude / v2, v1.Direction); } } There aren't any errors for the + and - operators, where I'm just working on a Vector<T>, but when I substitute a unit for T, suddenly it doesn't like it. Is there a way to make this work? I figured it would work, since Displacement implements the VectorUnit interface, and I have where T : VectorUnit in the struct header. Am I at least on the right track here? I'm new to C# so I have difficulty understanding what's going on sometimes.

    Read the article

  • Conversion constructor vs. conversion operator: precedence

    - by GRB
    Reading some questions here on SO about conversion operators and constructors got me thinking about the interaction between them, namely when there is an 'ambiguous' call. Consider the following code: class A; class B { public: B(){} B(const A&) //conversion constructor { cout << "called B's conversion constructor" << endl; } }; class A { public: operator B() //conversion operator { cout << "called A's conversion operator" << endl; return B(); } }; int main() { B b = A(); //what should be called here? apparently, A::operator B() return 0; } The above code displays "called A's conversion operator", meaning that the conversion operator is called as opposed to the constructor. If you remove/comment out the operator B() code from A, the compiler will happily switch over to using the constructor instead (with no other changes to the code). My questions are: Since the compiler doesn't consider B b = A(); to be an ambiguous call, there must be some type of precedence at work here. Where exactly is this precedence established? (a reference/quote from the C++ standard would be appreciated) From an object-oriented philosophical standpoint, is this the way the code should behave? Who knows more about how an A object should become a B object, A or B? According to C++, the answer is A -- is there anything in object-oriented practice that suggests this should be the case? To me personally, it would make sense either way, so I'm interested to know how the choice was made. Thanks in advance

    Read the article

  • Dilemma with two types and operator +

    - by user35443
    I have small problem with operators. I have this code: public class A { public string Name { get; set; } public A() { } public A(string Name) { this.Name = Name; } public static implicit operator B(A a) { return new B(a.Name); } public static A operator+(A a, A b) { return new A(a.Name + " " + b.Name); } } public class B { public string Name { get; set; } public B() { } public B(string Name) { this.Name = Name; } public static implicit operator A(B b) { return new A(b.Name); } public static B operator +(B b, B a) { return new B(b.Name + " " + a.Name); } } Now I want to know, which's conversion operator will be called and which's addition operator will be called in this operation: new A("a") + new B("b"); Will it be operator of A, or of B? (Or both?) Thanks....

    Read the article

  • How to modify a given class to use const operators

    - by zsero
    I am trying to solve my question regarding using push_back in more than one level. From the comments/answers it is clear that I have to: Create a copy operator which takes a const argument Modify all my operators to const But because this header file is given to me there is an operator what I cannot make into const. It is a simple: float & operator [] (int i) { return _item[i]; } In the given program, this operator is used to get and set data. My problem is that because I need to have this operator in the header file, I cannot turn all the other operators to const, what means I cannot insert a copy operator. How can I make all my operators into const, while preserving the functionality of the already written program? Here is the full declaration of the class: class Vector3f { float _item[3]; public: float & operator [] (int i) { return _item[i]; } Vector3f(float x, float y, float z) { _item[0] = x ; _item[1] = y ; _item[2] = z; }; Vector3f() {}; Vector3f & operator = ( const Vector3f& obj) { _item[0] = obj[0]; _item[1] = obj[1]; _item[2] = obj[2]; return *this; }; Vector3f & operator += ( const Vector3f & obj) { _item[0] += obj[0]; _item[1] += obj[1]; _item[2] += obj[2]; return *this; }; bool operator ==( const Vector3f & obj) { bool x = (_item[0] == obj[0]) && (_item[1] == obj[1]) && (_item[2] == obj[2]); return x; } // my copy operator Vector3f(const Vector3f& obj) { _item[0] += obj[0]; _item[1] += obj[1]; _item[2] += obj[2]; return this; } };

    Read the article

  • DIVIDE vs division operator in #dax

    - by Marco Russo (SQLBI)
    Alberto Ferrari wrote an interesting article about DIVIDE performance in DAX. This new function has been introduced in SQL Server Analysis Services 2012 SP1, so it is available also in Excel 2013 (which still doesn’t have other features/fixes introduced by following Cumulative Updates…). The idea that instead of writing: IF ( Sales[Quantity] <> 0, Sales[Amount] / Sales[Quantity], BLANK () ) you can write: DIVIDE ( Sales[Amount], Sales[Quantity] ) There is a third optional argument in DIVIDE that defines the result in case the denominator (second argument) is zero, and by default its value is BLANK, so I omitted the third argument in my example. Using DIVIDE is very important, especially when you use a measure in MDX (for example in an Excel PivotTable) because it raise the chance that the non empty evaluation for the result is evaluated in bulk mode instead of cell-by-cell. However, from a DAX point of view, you might find it’s better to use the standard division operator removing the IF statement. I suggest you to read Alberto’s article, because you will find that an expression applying a filter using FILTER is faster than using CALCULATE, which is against any rule of thumb you might have read until now! Again, this is not always true, and depends on many conditions – trying to simplify, we might say that for a simple calculation, the query plan generated by FILTER could be more efficient – but, as usual, it depends, and 90% of the times using FILTER instead of CALCULATE produces slower performance. Do not take anything for granted, and always check the query plan when performance are your first issue!

    Read the article

  • 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

  • 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

  • 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

  • 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

  • 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 is the rationale to non allow overloading of C++ conversions operator with non-member functio

    - by Vicente Botet Escriba
    C++0x has added explicit conversion operators, but they must always be defined as members of the Source class. The same applies to the assignment operator, it must be defined on the Target class. When the Source and Target classes of the needed conversion are independent of each other, neither the Source can define a conversion operator, neither the Target can define a constructor from a Source. Usually we get it by defining a specific function such as Target ConvertToTarget(Source& v); If C++0x allowed to overload conversion operator by non member functions we could for example define the conversion implicitly or explicitly between unrelated types. template < typename To, typename From operator To(const From& val); For example we could specialize the conversion from chrono::time_point to posix_time::ptime as follows template < class Clock, class Duration operator boost::posix_time::ptime( const boost::chrono::time_point& from) { using namespace boost; typedef chrono::time_point time_point_t; typedef chrono::nanoseconds duration_t; typedef duration_t::rep rep_t; rep_t d = chrono::duration_cast( from.time_since_epoch()).count(); rep_t sec = d/1000000000; rep_t nsec = d%1000000000; return posix_time::from_time_t(0)+ posix_time::seconds(static_cast(sec))+ posix_time::nanoseconds(nsec); } And use the conversion as any other conversion. So the question is: What is the rationale to non allow overloading of C++ conversions operator with non-member functions?

    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

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >