Search Results

Search found 20401 results on 817 pages for 'null coalescing operator'.

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

  • cast operator to base class within a thin wrapper derived class

    - by miked
    I have a derived class that's a very thin wrapper around a base class. Basically, I have a class that has two ways that it can be compared depending on how you interpret it so I created a new class that derives from the base class and only has new constructors (that just delegate to the base class) and a new operator==. What I'd like to do is overload the operator Base&() in the Derived class so in cases where I need to interpret it as the Base. For example: class Base { Base(stuff); Base(const Base& that); bool operator==(Base& rhs); //typical equality test }; class Derived : public Base { Derived(stuff) : Base(stuff) {}; Derived(const Base& that) : Base(that) {}; Derived(const Derived& that) : Base(that) {}; bool operator==(Derived& rhs); //special case equality test operator Base&() { return (Base&)*this; //Is this OK? It seems wrong to me. } }; If you want a simple example of what I'm trying to do, pretend I had a String class and String==String is the typical character by character comparison. But I created a new class CaseInsensitiveString that did a case insensitive compare on CaseInsensitiveString==CaseInsensitiveString but in all other cases just behaved like a String. it doesn't even have any new data members, just an overloaded operator==. (Please, don't tell me to use std::string, this is just an example!) Am I going about this right? Something seems fishy, but I can't put my finger on it.

    Read the article

  • Visual C++ doesn't operator<< overload

    - by PierreBdR
    I have a vector class that I want to be able to input/output from a QTextStream object. The forward declaration of my vector class is: namespace util { template <size_t dim, typename T> class Vector; } I define the operator<< as: namespace util { template <size_t dim, typename T> QTextStream& operator<<(QTextStream& out, const util::Vector<dim,T>& vec) { ... } template <size_t dim, typename T> QTextStream& operator>>(QTextStream& in,util::Vector<dim,T>& vec) { .. } } However, if I ty to use these operators, Visual C++ returns this error: error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'QTextStream' (or there is no acceptable conversion) A few things I tried: Originaly, the methods were defined as friends of the template, and it is working fine this way with g++. The methods have been moved outside the namespace util I changed the definition of the templates to fit what I found on various Visual C++ websites. The original friend declaration is: friend QTextStream& operator>>(QTextStream& ss, Vector& in) { ... } The "Visual C++ adapted" version is: friend QTextStream& operator>> <dim,T>(QTextStream& ss, Vector<dim,T>& in); with the function pre-declared before the class and implemented after. I checked the file is correctly included using: #pragma message ("Including vector header") And everything seems fine. Doesn anyone has any idea what might be wrong?

    Read the article

  • What are the default return values for operator< and operator[] in C++ (Visual Studio 6)?

    - by DustOff
    I've inherited a large Visual Studio 6 C++ project that needs to be translated for VS2005. Some of the classes defined operator< and operator[], but don't specify return types in the declarations. VS6 allows this, but not VS2005. I am aware that the C standard specifies that the default return type for normal functions is int, and I assumed VS6 might have been following that, but would this apply to C++ operators as well? Or could VS6 figure out the return type on its own? For example, the code defines a custom string class like this: class String { char arr[16]; public: operator<(const String& other) { return something1 < something2; } operator[](int index) { return arr[index]; } }; Would VS6 have simply put the return types for both as int, or would it have been smart enough to figure out that operator[] should return a char and operator< should return a bool (and not convert both results to int all the time)? Of course I have to add return types to make this code VS2005 C++ compliant, but I want to make sure to specify the same type as before, as to not immediately change program behavior (we're going for compatibility at the moment; we'll standardize things later).

    Read the article

  • What is the rationale to not allow overloading of C++ conversions operator with non-member function

    - 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<Clock, Duration>& from) { using namespace boost; typedef chrono::time_point<Clock, Duration> time_point_t; typedef chrono::nanoseconds duration_t; typedef duration_t::rep rep_t; rep_t d = chrono::duration_cast<duration_t>( 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<long>(sec))+ posix_time::nanoseconds(nsec); } And use the conversion as any other conversion. For a more complete description of the problem, see here or on my Boost.Conversion library.. So the question is: What is the rationale to non allow overloading of C++ conversions operator with non-member functions?

    Read the article

  • converting mysql database to sql server

    - by every_answer_gets_a_point
    i have a mysql database: /* MySQL Data Transfer Source Host: 10.0.0.5 Source Database: jnetdata Target Host: 10.0.0.5 Target Database: jnetdata Date: 5/26/2009 12:27:33 PM */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for chavrusas -- ---------------------------- CREATE TABLE `chavrusas` ( `id` int(11) NOT NULL auto_increment, `date_created` datetime default NULL, `luser_id` int(11) default NULL, `ruser_id` int(11) default NULL, `luser_type` varchar(50) default NULL, `ruser_type` varchar(50) default NULL, `SessionDay` varchar(250) default NULL, `SessionTime` datetime default NULL, `WeeklyReminder` tinyint(1) NOT NULL default '0', `reminder_phone` tinyint(1) NOT NULL default '0', `calling_card` varchar(50) default NULL, `active` tinyint(1) NOT NULL default '0', `notes` mediumtext, `ended` tinyint(1) NOT NULL default '0', `end_date` datetime default NULL, `initiated_by_student` tinyint(1) NOT NULL default '0', `initiated_by_volunteer` tinyint(1) NOT NULL default '0', `student_general_reason` varchar(50) default NULL, `volunteer_general_reason` varchar(50) default NULL, `student_reason` varchar(250) default NULL, `volunteer_reason` varchar(250) default NULL, `student_nli` tinyint(1) NOT NULL default '0', `volunteer_nli` tinyint(1) NOT NULL default '0', `jnet_initiated` tinyint(1) default '0', `belongs_to` varchar(50) default NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=5913 DEFAULT CHARSET=latin1; -- ---------------------------- -- Table structure for tbluseravailability -- ---------------------------- CREATE TABLE `tbluseravailability` ( `availability_id` int(11) NOT NULL auto_increment, `user_id` int(11) NOT NULL, `weekday_id` int(11) NOT NULL, `timeslot_id` int(11) NOT NULL, PRIMARY KEY (`availability_id`) ) ENGINE=MyISAM AUTO_INCREMENT=10865 DEFAULT CHARSET=latin1; -- ---------------------------- -- Table structure for tblusers -- ---------------------------- CREATE TABLE `tblusers` ( `id` int(11) NOT NULL auto_increment, `password` varchar(50) default NULL, `title` varchar(255) default NULL, `first` varchar(255) default NULL, `last` varchar(255) default NULL, `gender` varchar(255) default NULL, `address` varchar(255) default NULL, `address_2` varchar(255) default NULL, `city` varchar(255) default NULL, `state` varchar(255) default NULL, `postcode` varchar(255) default NULL, `country` varchar(255) default NULL, `email` varchar(255) default NULL, `emailnotes` varchar(255) default NULL, `Home_Phone` varchar(255) default NULL, `Office_Phone` varchar(255) default NULL, `Cell_Phone` varchar(255) default NULL, `Contact_Preference` varchar(255) default NULL, `Birthdate` datetime default NULL, `Age` varchar(255 and it goes on for about 10mb i need to convert it to ms sql, how do i do it?

    Read the article

  • How to set arrayList size as null?

    - by Jessy
    String a []= {null,null,null,null,null}; //add array to arraylist ArrayList<Object> choice = new ArrayList<Object>(Arrays.asList(a)); System.out.println(choice.size()); Why the size of the arrayList choice is 5 when all the elements have been set to null

    Read the article

  • SQL SERVER – Validating Spatial Object as NULL using IsNULL

    - by pinaldave
    Follow up questions are the most fun part of writing a blog post. Earlier I wrote about SQL SERVER – Validating Spatial Object with IsValidDetailed Function and today I received a follow up question on the same subject. The question was mainly about how NULL is handled by spatial functions. Well, NULL is NULL. It is very easy to work with NULL. There are two different ways to validate if the passed in the value is NULL or not. 1) Using IsNULL Function IsNULL function validates if the object is null or not, if object is not null it will return you value 0 and if object is NULL it will return you the value NULL. DECLARE @p GEOMETRY = 'Polygon((2 2, 3 3, 4 4, 5 5, 6 6, 2 2))' SELECT @p.ISNULL ObjIsNull GO DECLARE @p GEOMETRY = NULL SELECT @p.ISNULL ObjIsNull GO 2) Using IsValidDetailed Function IsValidateDetails function validates if the object is valid or not. If the object is valid it will return 24400: Valid but if the object is not valid it will give message with the error number. In case object is NULL it will return the value as NULL. DECLARE @p GEOMETRY = 'Polygon((2 2, 3 3, 4 4, 5 5, 6 6, 2 2))' SELECT @p.IsValidDetailed() IsValid GO DECLARE @p GEOMETRY = NULL SELECT @p.IsValidDetailed() IsValid GO When to use what? Now you can see that there are two different ways to validate the NULL values. I personally have no preference about using one over another. However, there is one clear difference between them. In case of the IsValidDetailed Function the return value is nvarchar(max) and it is not always possible to compare the value with nvarchar(max). Whereas the ISNULL function returns the bit value of 0 when the object is null and it is easy to determine if the object is null or not in the case of ISNULL function. Additionally, ISNULL function does not check if the object is valid or not and will return the value 0 if the object is not NULL. Now you know even though either of the function can be used in place of each other both have very specific use case. Use the one which fits your business case. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Function, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology Tagged: Spatial Database, SQL Spatial

    Read the article

  • Hello Operator, My Switch Is Bored

    - by Paul White
    This is a post for T-SQL Tuesday #43 hosted by my good friend Rob Farley. The topic this month is Plan Operators. I haven’t taken part in T-SQL Tuesday before, but I do like to write about execution plans, so this seemed like a good time to start. This post is in two parts. The first part is primarily an excuse to use a pretty bad play on words in the title of this blog post (if you’re too young to know what a telephone operator or a switchboard is, I hate you). The second part of the post looks at an invisible query plan operator (so to speak). 1. My Switch Is Bored Allow me to present the rare and interesting execution plan operator, Switch: Books Online has this to say about Switch: Following that description, I had a go at producing a Fast Forward Cursor plan that used the TOP operator, but had no luck. That may be due to my lack of skill with cursors, I’m not too sure. The only application of Switch in SQL Server 2012 that I am familiar with requires a local partitioned view: CREATE TABLE dbo.T1 (c1 int NOT NULL CHECK (c1 BETWEEN 00 AND 24)); CREATE TABLE dbo.T2 (c1 int NOT NULL CHECK (c1 BETWEEN 25 AND 49)); CREATE TABLE dbo.T3 (c1 int NOT NULL CHECK (c1 BETWEEN 50 AND 74)); CREATE TABLE dbo.T4 (c1 int NOT NULL CHECK (c1 BETWEEN 75 AND 99)); GO CREATE VIEW V1 AS SELECT c1 FROM dbo.T1 UNION ALL SELECT c1 FROM dbo.T2 UNION ALL SELECT c1 FROM dbo.T3 UNION ALL SELECT c1 FROM dbo.T4; Not only that, but it needs an updatable local partitioned view. We’ll need some primary keys to meet that requirement: ALTER TABLE dbo.T1 ADD CONSTRAINT PK_T1 PRIMARY KEY (c1);   ALTER TABLE dbo.T2 ADD CONSTRAINT PK_T2 PRIMARY KEY (c1);   ALTER TABLE dbo.T3 ADD CONSTRAINT PK_T3 PRIMARY KEY (c1);   ALTER TABLE dbo.T4 ADD CONSTRAINT PK_T4 PRIMARY KEY (c1); We also need an INSERT statement that references the view. Even more specifically, to see a Switch operator, we need to perform a single-row insert (multi-row inserts use a different plan shape): INSERT dbo.V1 (c1) VALUES (1); And now…the execution plan: The Constant Scan manufactures a single row with no columns. The Compute Scalar works out which partition of the view the new value should go in. The Assert checks that the computed partition number is not null (if it is, an error is returned). The Nested Loops Join executes exactly once, with the partition id as an outer reference (correlated parameter). The Switch operator checks the value of the parameter and executes the corresponding input only. If the partition id is 0, the uppermost Clustered Index Insert is executed, adding a row to table T1. If the partition id is 1, the next lower Clustered Index Insert is executed, adding a row to table T2…and so on. In case you were wondering, here’s a query and execution plan for a multi-row insert to the view: INSERT dbo.V1 (c1) VALUES (1), (2); Yuck! An Eager Table Spool and four Filters! I prefer the Switch plan. My guess is that almost all the old strategies that used a Switch operator have been replaced over time, using things like a regular Concatenation Union All combined with Start-Up Filters on its inputs. Other new (relative to the Switch operator) features like table partitioning have specific execution plan support that doesn’t need the Switch operator either. This feels like a bit of a shame, but perhaps it is just nostalgia on my part, it’s hard to know. Please do let me know if you encounter a query that can still use the Switch operator in 2012 – it must be very bored if this is the only possible modern usage! 2. Invisible Plan Operators The second part of this post uses an example based on a question Dave Ballantyne asked using the SQL Sentry Plan Explorer plan upload facility. If you haven’t tried that yet, make sure you’re on the latest version of the (free) Plan Explorer software, and then click the Post to SQLPerformance.com button. That will create a site question with the query plan attached (which can be anonymized if the plan contains sensitive information). Aaron Bertrand and I keep a close eye on questions there, so if you have ever wanted to ask a query plan question of either of us, that’s a good way to do it. The problem The issue I want to talk about revolves around a query issued against a calendar table. The script below creates a simplified version and adds 100 years of per-day information to it: USE tempdb; GO CREATE TABLE dbo.Calendar ( dt date NOT NULL, isWeekday bit NOT NULL, theYear smallint NOT NULL,   CONSTRAINT PK__dbo_Calendar_dt PRIMARY KEY CLUSTERED (dt) ); GO -- Monday is the first day of the week for me SET DATEFIRST 1;   -- Add 100 years of data INSERT dbo.Calendar WITH (TABLOCKX) (dt, isWeekday, theYear) SELECT CA.dt, isWeekday = CASE WHEN DATEPART(WEEKDAY, CA.dt) IN (6, 7) THEN 0 ELSE 1 END, theYear = YEAR(CA.dt) FROM Sandpit.dbo.Numbers AS N CROSS APPLY ( VALUES (DATEADD(DAY, N.n - 1, CONVERT(date, '01 Jan 2000', 113))) ) AS CA (dt) WHERE N.n BETWEEN 1 AND 36525; The following query counts the number of weekend days in 2013: SELECT Days = COUNT_BIG(*) FROM dbo.Calendar AS C WHERE theYear = 2013 AND isWeekday = 0; It returns the correct result (104) using the following execution plan: The query optimizer has managed to estimate the number of rows returned from the table exactly, based purely on the default statistics created separately on the two columns referenced in the query’s WHERE clause. (Well, almost exactly, the unrounded estimate is 104.289 rows.) There is already an invisible operator in this query plan – a Filter operator used to apply the WHERE clause predicates. We can see it by re-running the query with the enormously useful (but undocumented) trace flag 9130 enabled: Now we can see the full picture. The whole table is scanned, returning all 36,525 rows, before the Filter narrows that down to just the 104 we want. Without the trace flag, the Filter is incorporated in the Clustered Index Scan as a residual predicate. It is a little bit more efficient than using a separate operator, but residual predicates are still something you will want to avoid where possible. The estimates are still spot on though: Anyway, looking to improve the performance of this query, Dave added the following filtered index to the Calendar table: CREATE NONCLUSTERED INDEX Weekends ON dbo.Calendar(theYear) WHERE isWeekday = 0; The original query now produces a much more efficient plan: Unfortunately, the estimated number of rows produced by the seek is now wrong (365 instead of 104): What’s going on? The estimate was spot on before we added the index! Explanation You might want to grab a coffee for this bit. Using another trace flag or two (8606 and 8612) we can see that the cardinality estimates were exactly right initially: The highlighted information shows the initial cardinality estimates for the base table (36,525 rows), the result of applying the two relational selects in our WHERE clause (104 rows), and after performing the COUNT_BIG(*) group by aggregate (1 row). All of these are correct, but that was before cost-based optimization got involved :) Cost-based optimization When cost-based optimization starts up, the logical tree above is copied into a structure (the ‘memo’) that has one group per logical operation (roughly speaking). The logical read of the base table (LogOp_Get) ends up in group 7; the two predicates (LogOp_Select) end up in group 8 (with the details of the selections in subgroups 0-6). These two groups still have the correct cardinalities as trace flag 8608 output (initial memo contents) shows: During cost-based optimization, a rule called SelToIdxStrategy runs on group 8. It’s job is to match logical selections to indexable expressions (SARGs). It successfully matches the selections (theYear = 2013, is Weekday = 0) to the filtered index, and writes a new alternative into the memo structure. The new alternative is entered into group 8 as option 1 (option 0 was the original LogOp_Select): The new alternative is to do nothing (PhyOp_NOP = no operation), but to instead follow the new logical instructions listed below the NOP. The LogOp_GetIdx (full read of an index) goes into group 21, and the LogOp_SelectIdx (selection on an index) is placed in group 22, operating on the result of group 21. The definition of the comparison ‘the Year = 2013’ (ScaOp_Comp downwards) was already present in the memo starting at group 2, so no new memo groups are created for that. New Cardinality Estimates The new memo groups require two new cardinality estimates to be derived. First, LogOp_Idx (full read of the index) gets a predicted cardinality of 10,436. This number comes from the filtered index statistics: DBCC SHOW_STATISTICS (Calendar, Weekends) WITH STAT_HEADER; The second new cardinality derivation is for the LogOp_SelectIdx applying the predicate (theYear = 2013). To get a number for this, the cardinality estimator uses statistics for the column ‘theYear’, producing an estimate of 365 rows (there are 365 days in 2013!): DBCC SHOW_STATISTICS (Calendar, theYear) WITH HISTOGRAM; This is where the mistake happens. Cardinality estimation should have used the filtered index statistics here, to get an estimate of 104 rows: DBCC SHOW_STATISTICS (Calendar, Weekends) WITH HISTOGRAM; Unfortunately, the logic has lost sight of the link between the read of the filtered index (LogOp_GetIdx) in group 22, and the selection on that index (LogOp_SelectIdx) that it is deriving a cardinality estimate for, in group 21. The correct cardinality estimate (104 rows) is still present in the memo, attached to group 8, but that group now has a PhyOp_NOP implementation. Skipping over the rest of cost-based optimization (in a belated attempt at brevity) we can see the optimizer’s final output using trace flag 8607: This output shows the (incorrect, but understandable) 365 row estimate for the index range operation, and the correct 104 estimate still attached to its PhyOp_NOP. This tree still has to go through a few post-optimizer rewrites and ‘copy out’ from the memo structure into a tree suitable for the execution engine. One step in this process removes PhyOp_NOP, discarding its 104-row cardinality estimate as it does so. To finish this section on a more positive note, consider what happens if we add an OVER clause to the query aggregate. This isn’t intended to be a ‘fix’ of any sort, I just want to show you that the 104 estimate can survive and be used if later cardinality estimation needs it: SELECT Days = COUNT_BIG(*) OVER () FROM dbo.Calendar AS C WHERE theYear = 2013 AND isWeekday = 0; The estimated execution plan is: Note the 365 estimate at the Index Seek, but the 104 lives again at the Segment! We can imagine the lost predicate ‘isWeekday = 0’ as sitting between the seek and the segment in an invisible Filter operator that drops the estimate from 365 to 104. Even though the NOP group is removed after optimization (so we don’t see it in the execution plan) bear in mind that all cost-based choices were made with the 104-row memo group present, so although things look a bit odd, it shouldn’t affect the optimizer’s plan selection. I should also mention that we can work around the estimation issue by including the index’s filtering columns in the index key: CREATE NONCLUSTERED INDEX Weekends ON dbo.Calendar(theYear, isWeekday) WHERE isWeekday = 0 WITH (DROP_EXISTING = ON); There are some downsides to doing this, including that changes to the isWeekday column may now require Halloween Protection, but that is unlikely to be a big problem for a static calendar table ;)  With the updated index in place, the original query produces an execution plan with the correct cardinality estimation showing at the Index Seek: That’s all for today, remember to let me know about any Switch plans you come across on a modern instance of SQL Server! Finally, here are some other posts of mine that cover other plan operators: Segment and Sequence Project Common Subexpression Spools Why Plan Operators Run Backwards Row Goals and the Top Operator Hash Match Flow Distinct Top N Sort Index Spools and Page Splits Singleton and Range Seeks Bitmaps Hash Join Performance Compute Scalar © 2013 Paul White – All Rights Reserved Twitter: @SQL_Kiwi

    Read the article

  • Dereferencing the null pointer

    - by zilgo
    The standard says that dereferencing the null pointer leads to undefined behaviour. But what is "the null pointer"? In the following code, what we call "the null pointer": struct X { static X* get() { return reinterpret_cast<X*>(1); } void f() { } }; int main() { X* x = 0; (*x).f(); // the null pointer? (1) x = X::get(); (*x).f(); // the null pointer? (2) x = reinterpret_cast<X*>( X::get() - X::get() ); (*x).f(); // the null pointer? (3) (*(X*)0).f(); // I think that this the only null pointer here (4) } My thought is that dereferencing of the null pointer takes place only in the last case. Am I right? Is there difference between compile time null pointers and runtime according to C++ Standard?

    Read the article

  • sql query where parameters null not null

    - by Laziale
    I am trying to do a sql query and to build the where condition dynamically depending if the parameters are null or no. I have something like this: SELECT tblOrder.ProdOrder, tblOrder.Customer FROM tblOrder CASE WHEN @OrderId IS NOT NULL THEN WHERE tblOrder.OrderId = @OrderId ELSE END CASE WHEN @OrderCustomer IS NOT NULL THEN AND tblOrder.OrderCustomer = @OrderCustomer ELSE END END This doesn't work, but this is just a small prototype how to assemble the query, so if the orderid is not null include in the where clause, or if the ordercustomer is not null include in the where clause. But I see problem here, for example if the ordercustomer is not null but the orderid is null, there will be error because the where keyword is not included. Any advice how I can tackle this problem. Thanks in advance, Laziale

    Read the article

  • Null Values And The T-SQL IN Operator

    - by Jesse
    I came across some unexpected behavior while troubleshooting a failing test the other day that took me long enough to figure out that I thought it was worth sharing here. I finally traced the failing test back to a SELECT statement in a stored procedure that was using the IN t-sql operator to exclude a certain set of values. Here’s a very simple example table to illustrate the issue: Customers CustomerId INT, NOT NULL, Primary Key CustomerName nvarchar(100) NOT NULL SalesRegionId INT NULL   The ‘SalesRegionId’ column contains a number representing the sales region that the customer belongs to. This column is nullable because new customers get created all the time but assigning them to sales regions is a process that is handled by a regional manager on a periodic basis. For the purposes of this example, the Customers table currently has the following rows: CustomerId CustomerName SalesRegionId 1 Customer A 1 2 Customer B NULL 3 Customer C 4 4 Customer D 2 5 Customer E 3   How could we write a query against this table for all customers that are NOT in sales regions 2 or 4? You might try something like this: 1: SELECT 2: CustomerId, 3: CustomerName, 4: SalesRegionId 5: FROM Customers 6: WHERE SalesRegionId NOT IN (2,4)   Will this work? In short, no; at least not in the way that you might expect. Here’s what this query will return given the example data we’re working with: CustomerId CustomerName SalesRegionId 1 Customer A 1 5 Customer E 5   I was expecting that this query would also return ‘Customer B’, since that customer has a NULL SalesRegionId. In my mind, having a customer with no sales region should be included in a set of customers that are not in sales regions 2 or 4.When I first started troubleshooting my issue I made note of the fact that this query should probably be re-written without the NOT IN clause, but I didn’t suspect that the NOT IN clause was actually the source of the issue. This particular query was only one minor piece in a much larger process that was being exercised via an automated integration test and I simply made a poor assumption that the NOT IN would work the way that I thought it should. So why doesn’t this work the way that I thought it should? From the MSDN documentation on the t-sql IN operator: If the value of test_expression is equal to any value returned by subquery or is equal to any expression from the comma-separated list, the result value is TRUE; otherwise, the result value is FALSE. Using NOT IN negates the subquery value or expression. The key phrase out of that quote is, “… is equal to any expression from the comma-separated list…”. The NULL SalesRegionId isn’t included in the NOT IN because of how NULL values are handled in equality comparisons. From the MSDN documentation on ANSI_NULLS: The SQL-92 standard requires that an equals (=) or not equal to (<>) comparison against a null value evaluates to FALSE. When SET ANSI_NULLS is ON, a SELECT statement using WHERE column_name = NULL returns zero rows even if there are null values in column_name. A SELECT statement using WHERE column_name <> NULL returns zero rows even if there are nonnull values in column_name. In fact, the MSDN documentation on the IN operator includes the following blurb about using NULL values in IN sub-queries or expressions that are used with the IN operator: Any null values returned by subquery or expression that are compared to test_expression using IN or NOT IN return UNKNOWN. Using null values in together with IN or NOT IN can produce unexpected results. If I were to include a ‘SET ANSI_NULLS OFF’ command right above my SELECT statement I would get ‘Customer B’ returned in the results, but that’s definitely not the right way to deal with this. We could re-write the query to explicitly include the NULL value in the WHERE clause: 1: SELECT 2: CustomerId, 3: CustomerName, 4: SalesRegionId 5: FROM Customers 6: WHERE (SalesRegionId NOT IN (2,4) OR SalesRegionId IS NULL)   This query works and properly includes ‘Customer B’ in the results, but I ultimately opted to re-write the query using a LEFT OUTER JOIN against a table variable containing all of the values that I wanted to exclude because, in my case, there could potentially be several hundred values to be excluded. If we were to apply the same refactoring to our simple sales region example we’d end up with: 1: DECLARE @regionsToIgnore TABLE (IgnoredRegionId INT) 2: INSERT @regionsToIgnore values (2),(4) 3:  4: SELECT 5: c.CustomerId, 6: c.CustomerName, 7: c.SalesRegionId 8: FROM Customers c 9: LEFT OUTER JOIN @regionsToIgnore r ON r.IgnoredRegionId = c.SalesRegionId 10: WHERE r.IgnoredRegionId IS NULL By performing a LEFT OUTER JOIN from Customers to the @regionsToIgnore table variable we can simply exclude any rows where the IgnoredRegionId is null, as those represent customers that DO NOT appear in the ignored regions list. This approach will likely perform better if the number of sales regions to ignore gets very large and it also will correctly include any customers that do not yet have a sales region.

    Read the article

  • Overloading operator>> to a char buffer in C++ - can I tell the stream length?

    - by exscape
    I'm on a custom C++ crash course. I've known the basics for many years, but I'm currently trying to refresh my memory and learn more. To that end, as my second task (after writing a stack class based on linked lists), I'm writing my own string class. It's gone pretty smoothly until now; I want to overload operator that I can do stuff like cin my_string;. The problem is that I don't know how to read the istream properly (or perhaps the problem is that I don't know streams...). I tried a while (!stream.eof()) loop that .read()s 128 bytes at a time, but as one might expect, it stops only on EOF. I want it to read to a newline, like you get with cin to a std::string. My string class has an alloc(size_t new_size) function that (re)allocates memory, and an append(const char *) function that does that part, but I obviously need to know the amount of memory to allocate before I can write to the buffer. Any advice on how to implement this? I tried getting the istream length with seekg() and tellg(), to no avail (it returns -1), and as I said looping until EOF (doesn't stop reading at a newline) reading one chunk at a time.

    Read the article

  • Overload assignment operator for assigning sql::ResultSet to struct tm

    - by Luke Mcneice
    Are there exceptions for types which can't have thier assignment operator overloaded? Specifically, I'm wanting to overload the assignment operator of a struct tm (from time.h) so I can assign a sql::ResultSet to it. I already have the conversion logic: sscanf(sqlresult->getString("StoredAt").c_str(), "%d-%d-%d %d:%d:%d", &TempTimeStruct->tm_year, &TempTimeStruct->tm_mon, &TempTimeStruct->tm_mday, &TempTimeStruct->tm_hour, &TempTimeStruct->tm_min, &TempTimeStruct->tm_sec); I tried the overload with this: tm& tm::operator=(sql::ResultSet & results) { /*CODE*/ return *this; } However VS08 reports: error C2511: 'tm &tm::operator =(sql::ResultSet &)' : overloaded member function not found in 'tm'

    Read the article

  • How to prevent a globally overridden "new" operator from being linked in from external library

    - by mprudhom
    In our iPhone XCode 3.2.1 project, we're linking in 2 external static C++ libraries, libBlue.a and libGreen.a. libBlue.a globally overrides the "new" operator for it's own memory management. However, when we build our project, libGreen.a winds up using libBlue's new operator, which results in a crash (presumably because libBlue.a is making assumptions about the kinds of structures being allocated). Both libBlue.a and libGreen.a are provided by 3rd parties, so we can't change any of their source code or build options. When we remove libBlue.a from the project, libGreen.a doesn't have any issues. However, no amount of shuffling the linking order of the libraries seems to fix the problem, nor does any experimentation with the various linking flags. Is there some way to tell XCode to tell the linker to "have libGreen's use of the new operator use the standard C++ new operator rather than the one redefined by libBlue"?

    Read the article

  • overloading friend operator<< for template class

    - by starcorn
    Hello, I have read couple of the question regarding my problem on stackoverflow now, and none of it seems to solve my problem. Or I maybe have done it wrong... The overloaded << if I make it into an inline function. But how do I make it work in my case? warning: friend declaration std::ostream& operator<<(std::ostream&, const D<classT>&)' declares a non-template function warning: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) -Wno-non-template-friend disables this warning /tmp/cc6VTWdv.o:uppgift4.cc:(.text+0x180): undefined reference to operator<<(std::basic_ostream<char, std::char_traits<char> >&, D<int> const&)' collect2: ld returned 1 exit status template <class T> T my_max(T a, T b) { if(a > b) return a; else return b; } template <class classT> class D { public: D(classT in) : d(in) {}; bool operator>(const D& rhs) const; classT operator=(const D<classT>& rhs); friend ostream& operator<< (ostream & os, const D<classT>& rhs); private: classT d; }; int main() { int i1 = 1; int i2 = 2; D<int> d1(i1); D<int> d2(i2); cout << my_max(d1,d2) << endl; return 0; } template <class classT> ostream& operator<<(ostream &os, const D<classT>& rhs) { os << rhs.d; return os; }

    Read the article

  • Overload operator in F#

    - by forki23
    Hi, I would like to overload the (/) operator in F# for strings and preserve the meaning for numbers. /// Combines to path strings let (/) path1 path2 = Path.Combine(path1,path2) let x = 3 / 4 // doesn't compile If I try the following I get "Warning 29 Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead." /// Combines to path strings type System.String with static member (/) (path1,path2) = Path.Combine(path1,path2) Any ideas? Regards, forki

    Read the article

  • C++ overide global operator comma gives error

    - by uray
    the second function gives error C2803 http://msdn.microsoft.com/en-us/library/zy7kx46x%28VS.80%29.aspx : 'operator ,' must have at least one formal parameter of class type. any clue? template<class T,class A = std::allocator<T>> class Sequence : public std::vector<T,A> { public: Sequence<T,A>& operator,(const T& a) { this->push_back(a); return *this; } Sequence<T,A>& operator,(const Sequence<T,A>& a) { for(Sequence<T,A>::size_type i=0 ; i<a.size() ; i++) { this->push_back(a.at(i)); } return *this; } }; //this works! template<typename T> Sequence<T> operator,(const T& a, const T&b) { Sequence<T> seq; seq.push_back(a); seq.push_back(b); return seq; } //this gives error C2803! Sequence<double> operator,(const double& a, const double& b) { Sequence<double> seq; seq.push_back(a); seq.push_back(b); return seq; }

    Read the article

  • Operator() as a subscript (C++)

    - by Ivan Gromov
    I use operator() as a subscript operator this way: double CVector::operator() (int i) const { if (i >= 0 && i < this->size) return this->data[i]; else return 0; } double& CVector::operator() (int i) { return (this->data[i]); } It works when I get values, but I get an error when I try to write assign a value using a(i) = 1; UPD: Error text: Unhandled exception at 0x651cf54a (msvcr100d.dll) in CG.exe: 0xC0000005: Access violation reading location 0xccccccc0.

    Read the article

  • What is an overloaded operator in c++?

    - by Jeff
    I realize this is a basic question but I have searched online, been to cplusplus.com, read through my book, and I can't seem to grasp the concept of overloaded operators. A specific example from cplusplus.com is: // vectors: overloading operators example #include <iostream> using namespace std; class CVector { public: int x,y; CVector () {}; CVector (int,int); CVector operator + (CVector); }; CVector::CVector (int a, int b) { x = a; y = b; } CVector CVector::operator+ (CVector param) { CVector temp; temp.x = x + param.x; temp.y = y + param.y; return (temp); } int main () { CVector a (3,1); CVector b (1,2); CVector c; c = a + b; cout << c.x << "," << c.y; return 0; } from http://www.cplusplus.com/doc/tutorial/classes2/ but reading through it I'm still not understanding them at all. I just need a basic example of the point of the overloaded operator (which I assume is the "CVector CVector::operator+ (CVector param)"). There's also this example from wikipedia: Time operator+(const Time& lhs, const Time& rhs) { Time temp = lhs; temp.seconds += rhs.seconds; if (temp.seconds >= 60) { temp.seconds -= 60; temp.minutes++; } temp.minutes += rhs.minutes; if (temp.minutes >= 60) { temp.minutes -= 60; temp.hours++; } temp.hours += rhs.hours; return temp; } from "http://en.wikipedia.org/wiki/Operator_overloading" The current assignment I'm working on I need to overload a ++ and a -- operator. Thanks in advance for the information and sorry about the somewhat vague question, unfortunately I'm just not sure on it at all.

    Read the article

  • Must parameter of assignment operator be reference?

    - by Tim
    When overloading assignment operator of a class in C++, must its parameter be reference? For example, class MyClass { public: ... MyClass & operator=(const MyClass &rhs); ... } Can it be class MyClass { public: ... MyClass & operator=(const MyClass rhs); ... } ? Thanks!

    Read the article

  • Operator overloading in C++

    - by user265260
    If you overload - like operator-(), it is to be used to the left of the object, however overloading () like operator()() it is used to the right of the object. How do we know which operator is to be used on the left and which ones to be used on the right?

    Read the article

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