Search Results

Search found 640 results on 26 pages for 'apophenia overload'.

Page 7/26 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Is extending a base class with non-virtual destructor dangerous in C++

    - by Akusete
    Take the following code class A { }; class B : public A { }; class C : public A { int x; }; int main (int argc, char** argv) { A* b = new B(); A* c = new C(); //in both cases, only ~A() is called, not ~B() or ~C() delete b; //is this ok? delete c; //does this line leak memory? return 0; } when calling delete on a class with a non-virtual destructor with member functions (like class C), can the memory allocator tell what the proper size of the object is? If not, is memory leaked? Secondly, if the class has no member functions, and no explicit destructor behaviour (like class B), is everything ok? I ask this because I wanted to create a class to extend std::string, (which I know is not recommended, but for the sake of the discussion just bear with it), and overload the +=,+ operator. -Weffc++ gives me a warning because std::string has a non virtual destructor, but does it matter if the sub-class has no members and does not need to do anything in its destructor? -- FYI the += overload was to do proper file path formatting, so the path class could be used like class path : public std::string { //... overload, +=, + //... add last_path_component, remove_path_component, ext, etc... }; path foo = "/some/file/path"; foo = foo + "filename.txt"; //and so on... I just wanted to make sure someone doing this path* foo = new path(); std::string* bar = foo; delete bar; would not cause any problems with memory allocation

    Read the article

  • Why is Attributes.IsDefined() missing overloads?

    - by Hans Passant
    Inspired by an SO question. The Attribute class has several overloads for the IsDefined() method. Covered are attributes applied to Assembly, Module, MemberInfo, ParameterInfo. The MemberInfo overload covers PropertyInfo, FieldInfo, EventInfo, MethodInfo, ConstructorInfo. That takes care of most of the AttributeTargets. Except for one biggy: there is no overload for Attribute.IsDefined(Type, Type) so that you could check if an attribute is defined on a class. Or a struct, delegate or enum for that matter. Not that this is a real problem, Type.GetCustomAttributes() can fix that. But all of the BlahInfo types have this too. I wonder at the lack of symmetry. I can't put a finger on why this would be problem for Type. Guessing at an inheritance problem doesn't explain it to me. Having ValueType in the mix might be a lead, still doesn't make sense. I don't buy "they forgot", they never do. Why is this overload missing?

    Read the article

  • C++11 Tidbits: access control under SFINAE conditions

    - by Paolo Carlini
    Lately I have been spending quite a bit of time on the SFINAE ("Substitution failure is not an error") features of C++, fixing and tweaking various bits of the GCC implementation. An important missing piece was the implementation of the resolution of DR 1170 which, in a nutshell, mandates that access checking is done as part of the substitution process. Consider: class C { typedef int type; }; template <class T, class = typename T::type> auto f(int) - char; template <class> auto f(...) -> char (&)[2]; static_assert (sizeof(f<C>(0)) == 2, "Ouch"); According to the resolution, the static_assert should not fire, and the snippet should compile successfully. The reason being that the first f overload must be removed from the candidate set because C::type is private to C. On the other hand, before the resolution of DR 1170, the expected behavior was for the first overload to remain in the candidate set, win over the second one, to eventually lead to an access control error (*). GCC mainline (would be 4.8) finally implements the DR, thus benefiting the many modern programming techniques heavily exploiting SFINAE, among which certainly the GNU C++ runtime library itself, which relies on it for the internals of <type_traits> and in several other places. Note that the resolution of the DR is active even in C++98 mode, not just in C++11 mode, because it turned out that the traditional behavior, as implemented in GCC, wasn't fully consistent in all the possible circumstances. (*) In practice, GCC didn't really implement this, the static_assert triggered instead.

    Read the article

  • Handling Types for Real and Complex Matrices in a BLAS Wrapper

    - by mga
    I come from a C background and I'm now learning OOP with C++. As an exercise (so please don't just say "this already exists"), I want to implement a wrapper for BLAS that will let the user write matrix algebra in an intuitive way (e.g. similar to MATLAB) e.g.: A = B*C*D.Inverse() + E.Transpose(); My problem is how to go about dealing with real (R) and complex (C) matrices, because of C++'s "curse" of letting you do the same thing in N different ways. I do have a clear idea of what it should look like to the user: s/he should be able to define the two separately, but operations would return a type depending on the types of the operands (R*R = R, C*C = C, R*C = C*R = C). Additionally R can be cast into C and vice versa (just by setting the imaginary parts to 0). I have considered the following options: As a real number is a special case of a complex number, inherit CMatrix from RMatrix. I quickly dismissed this as the two would have to return different types for the same getter function. Inherit RMatrix and CMatrix from Matrix. However, I can't really think of any common code that would go into Matrix (because of the different return types). Templates. Declare Matrix<T> and declare the getter function as T Get(int i, int j), and operator functions as Matrix *(Matrix RHS). Then specialize Matrix<double> and Matrix<complex>, and overload the functions. Then I couldn't really see what I would gain with templates, so why not just define RMatrix and CMatrix separately from each other, and then overload functions as necessary? Although this last option makes sense to me, there's an annoying voice inside my head saying this is not elegant, because the two are clearly related. Perhaps I'm missing an appropriate design pattern? So I guess what I'm looking for is either absolution for doing this, or advice on how to do better.

    Read the article

  • forward same port but for two different IPs (cisco)

    - by Colin
    Hi! I have a cisco running IOS 12.0(25) responding to two different IPs addresses: IP_A and IP_B. Behind this router I also have two different servers: server_A and server_B. What I want is to forward port 22 to both servers, so: IP_A, port22 -> server_A, port22 IP_B, port22 -> server_B, port22 ATM this only works for one of them (server_A), this is my config: interface Ethernet0/0 description Internet ip address IP_A 255.255.255.0 ip address IP_B 255.255.255.0 secondary no ip directed-broadcast ip nat outside no ip mroute-cache no cdp enable ip nat pool pool_A IP_A IP_A netmask 255.255.255.0 ip nat pool pool_B IP_B IP_B netmask 255.255.255.0 ip nat inside source list A pool pool_A overload ip nat inside source list B pool pool_B overload ip nat inside source static tcp server_B 22 IP_B 22 extendable ip nat inside source static tcp server_A 22 IP_A 22 extendable access-list A permit server_A access-list B permit server_B

    Read the article

  • How do I imply code contracts of chained methods to avoid superfluous checks while chaining?

    - by Sandor Drieënhuizen
    I'm using Code Contracts in C# 4.0. I'm applying the usual static method chaining to simulate optional parameters (I know C# 4.0 supports optional parameters but I really don't want to use them). The thing is that my contract requirements are executed twice (or possibly the number of chained overloads I'd implement) if I call the Init(string , string[]) method -- an obvious effect from the sample source code below. This can be expensive, especially due to relatively expensive requirements like the File.Exists I use. public static void Init(string configurationPath, string[] mappingAssemblies) { // The static contract checker 'makes' me put these here as well as // in the overload below. Contract.Requires<ArgumentNullException>(configurationPath != null, "configurationPath"); Contract.Requires<ArgumentException>(configurationPath.Length > 0, "configurationPath is an empty string."); Contract.Requires<FileNotFoundException>(File.Exists(configurationPath), configurationPath); Contract.Requires<ArgumentNullException>(mappingAssemblies != null, "mappingAssemblies"); Contract.ForAll<string>(mappingAssemblies, (n) => File.Exists(n)); Init(configurationPath, mappingAssemblies, null); } public static void Init(string configurationPath, string[] mappingAssemblies, string optionalArgument) { // This is the main implementation of Init and all calls to chained // overloads end up here. Contract.Requires<ArgumentNullException>(configurationPath != null, "configurationPath"); Contract.Requires<ArgumentException>(configurationPath.Length > 0, "configurationPath is an empty string."); Contract.Requires<FileNotFoundException>(File.Exists(configurationPath), configurationPath); Contract.Requires<ArgumentNullException>(mappingAssemblies != null, "mappingAssemblies"); Contract.ForAll<string>(mappingAssemblies, (n) => File.Exists(n)); //... } If however, I remove the requirements from that method, the static checker complains that the requirements of the Init(string, string[], string) overload are not met. I reckon that the static checker doesn't understand that there requirements of the Init(string, string[], string) overload implicitly apply to the Init(string, string[]) method as well; something that would be perfectly deductable from the code IMO. This is the situation I would like to achieve: public static void Init(string configurationPath, string[] mappingAssemblies) { // I don't want to repeat the requirements here because they will always // be checked in the overload called here. Init(configurationPath, mappingAssemblies, null); } public static void Init(string configurationPath, string[] mappingAssemblies, string optionalArgument) { // This is the main implementation of Init and all calls to chained // overloads end up here. Contract.Requires<ArgumentNullException>(configurationPath != null, "configurationPath"); Contract.Requires<ArgumentException>(configurationPath.Length > 0, "configurationPath is an empty string."); Contract.Requires<FileNotFoundException>(File.Exists(configurationPath), configurationPath); Contract.Requires<ArgumentNullException>(mappingAssemblies != null, "mappingAssemblies"); Contract.ForAll<string>(mappingAssemblies, (n) => File.Exists(n)); //... } So, my question is this: is there a way to have the requirements of Init(string, string[], string) implicitly apply to Init(string, string[]) automatically?

    Read the article

  • Delphi 5: Ideas for simulating "Obsolete" or "Deprecated" methods?

    - by Ian Boyd
    i want to mark a method as obsolete, but Delphi 5 doesn't have such a feature. For the sake of an example, here is a made-up method with it's deprecated and new preferred form: procedure TStormPeaksQuest.BlowHodirsHorn; overload; //obsolete procedure TStormPeaksQuest.BlowHodirsHorn(UseProtection: Boolean); overload; Note: For this hypothetical example, we assume that using the parameterless version is just plain bad. There are problems with not "using protection" - which have no good solution. Nobody likes having to use protection, but nobody wants to not use protection. So we make the caller decide if they want to use protection or not when blowing Hodir's horn. If we default the parameterless version to continue not using protection: procedure TStormPeaksQuest.BlowHodirsHorn; begin BlowHodirsHorn(False); //No protection. Bad! end; then the developer is at risk of all kinds of nasty stuff. If we force the parameterless version to use protection: procedure TStormPeaksQuest.BlowHodirsHorn; begin BlowHodirsHorn(True); //Use protection; crash if there isn't any end; then there's a potential for problems if the developer didn't get any protection, or doesn't own any. Now i could rename the obsolete method: procedure TStormPeaksQuest.BlowHodirsHorn_Deprecatedd; overload; //obsolete procedure TStormPeaksQuest.BlowHodirsHorn(UseProtection: Boolean); overload; But that will cause a compile error, and people will bitch at me (and i really don't want to hear their whining). i want them to get a nag, rather than an actual error. i thought about adding an assertion: procedure TStormPeaksQuest.BlowHodirsHorn; //obsolete begin Assert(false, 'TStormPeaksQuest.BlowHodirsHorn is deprecated. Use BlowHodirsHorn(Boolean)'); ... end; But i cannot guarantee that the developer won't ship a version without assertions, causing a nasty crash for the customer. i thought about using only throwing an assertion if the developer is debugging: procedure TStormPeaksQuest.BlowHodirsHorn; //obsolete begin if DebugHook > 0 then Assert(false, 'TStormPeaksQuest.BlowHodirsHorn is deprecated. Use BlowHodirsHorn(Boolean)'); ... end; But i really don't want to be causing a crash at all. i thought of showing a MessageDlg if they're in the debugger (which is a technique i've done in the past): procedure TStormPeaksQuest.BlowHodirsHorn; //obsolete begin if DebugHook > 0 then MessageDlg('TStormPeaksQuest.BlowHodirsHorn is deprecated. Use BlowHodirsHorn(Boolean)', mtWarning, [mbOk], 0); ... end; but that is still too disruptive. And it has caused problems where the code is stuck at showing a modal dialog, but the dialog box wasn't obviously visible. i was hoping for some sort of warning message that will sit there nagging them - until they gouge their eyes out and finally change their code. i thought perhaps if i added an unused variable: procedure TStormPeaksQuest.BlowHodirsHorn; //obsolete var ThisMethodIsObsolete: Boolean; begin ... end; i was hoping this would cause a hint only if someone referenced the code. But Delphi shows a hint even if you don't call actually use the obsolete method. Can anyone think of anything else?

    Read the article

  • Templated << friend not working when in interrelationship with other templated union types

    - by Dwight
    While working on my basic vector library, I've been trying to use a nice syntax for swizzle-based printing. The problem occurs when attempting to print a swizzle of a different dimension than the vector in question. In GCC 4.0, I originally had the friend << overloaded functions (with a body, even though it duplicated code) for every dimension in each vector, which caused the code to work, even if the non-native dimension code never actually was called. This failed in GCC 4.2. I recently realized (silly me) that only the function declaration was needed, not the body of the code, so I did that. Now I get the same warning on both GCC 4.0 and 4.2: LINE 50 warning: friend declaration 'std::ostream& operator<<(std::ostream&, const VECTOR3<TYPE>&)' declares a non-template function Plus the five identical warnings more for the other function declarations. The below example code shows off exactly what's going on and has all code necessary to reproduce the problem. #include <iostream> // cout, endl #include <sstream> // ostream, ostringstream, string using std::cout; using std::endl; using std::string; using std::ostream; // Predefines template <typename TYPE> union VECTOR2; template <typename TYPE> union VECTOR3; template <typename TYPE> union VECTOR4; typedef VECTOR2<float> vec2; typedef VECTOR3<float> vec3; typedef VECTOR4<float> vec4; template <typename TYPE> union VECTOR2 { private: struct { TYPE x, y; } v; struct s1 { protected: TYPE x, y; }; struct s2 { protected: TYPE x, y; }; struct s3 { protected: TYPE x, y; }; struct s4 { protected: TYPE x, y; }; struct X : s1 { operator TYPE() const { return s1::x; } }; struct XX : s2 { operator VECTOR2<TYPE>() const { return VECTOR2<TYPE>(s2::x, s2::x); } }; struct XXX : s3 { operator VECTOR3<TYPE>() const { return VECTOR3<TYPE>(s3::x, s3::x, s3::x); } }; struct XXXX : s4 { operator VECTOR4<TYPE>() const { return VECTOR4<TYPE>(s4::x, s4::x, s4::x, s4::x); } }; public: VECTOR2() {} VECTOR2(const TYPE& x, const TYPE& y) { v.x = x; v.y = y; } X x; XX xx; XXX xxx; XXXX xxxx; // Overload for cout friend ostream& operator<<(ostream& os, const VECTOR2<TYPE>& toString) { os << "(" << toString.v.x << ", " << toString.v.y << ")"; return os; } friend ostream& operator<<(ostream& os, const VECTOR3<TYPE>& toString); friend ostream& operator<<(ostream& os, const VECTOR4<TYPE>& toString); }; template <typename TYPE> union VECTOR3 { private: struct { TYPE x, y, z; } v; struct s1 { protected: TYPE x, y, z; }; struct s2 { protected: TYPE x, y, z; }; struct s3 { protected: TYPE x, y, z; }; struct s4 { protected: TYPE x, y, z; }; struct X : s1 { operator TYPE() const { return s1::x; } }; struct XX : s2 { operator VECTOR2<TYPE>() const { return VECTOR2<TYPE>(s2::x, s2::x); } }; struct XXX : s3 { operator VECTOR3<TYPE>() const { return VECTOR3<TYPE>(s3::x, s3::x, s3::x); } }; struct XXXX : s4 { operator VECTOR4<TYPE>() const { return VECTOR4<TYPE>(s4::x, s4::x, s4::x, s4::x); } }; public: VECTOR3() {} VECTOR3(const TYPE& x, const TYPE& y, const TYPE& z) { v.x = x; v.y = y; v.z = z; } X x; XX xx; XXX xxx; XXXX xxxx; // Overload for cout friend ostream& operator<<(ostream& os, const VECTOR3<TYPE>& toString) { os << "(" << toString.v.x << ", " << toString.v.y << ", " << toString.v.z << ")"; return os; } friend ostream& operator<<(ostream& os, const VECTOR2<TYPE>& toString); friend ostream& operator<<(ostream& os, const VECTOR4<TYPE>& toString); }; template <typename TYPE> union VECTOR4 { private: struct { TYPE x, y, z, w; } v; struct s1 { protected: TYPE x, y, z, w; }; struct s2 { protected: TYPE x, y, z, w; }; struct s3 { protected: TYPE x, y, z, w; }; struct s4 { protected: TYPE x, y, z, w; }; struct X : s1 { operator TYPE() const { return s1::x; } }; struct XX : s2 { operator VECTOR2<TYPE>() const { return VECTOR2<TYPE>(s2::x, s2::x); } }; struct XXX : s3 { operator VECTOR3<TYPE>() const { return VECTOR3<TYPE>(s3::x, s3::x, s3::x); } }; struct XXXX : s4 { operator VECTOR4<TYPE>() const { return VECTOR4<TYPE>(s4::x, s4::x, s4::x, s4::x); } }; public: VECTOR4() {} VECTOR4(const TYPE& x, const TYPE& y, const TYPE& z, const TYPE& w) { v.x = x; v.y = y; v.z = z; v.w = w; } X x; XX xx; XXX xxx; XXXX xxxx; // Overload for cout friend ostream& operator<<(ostream& os, const VECTOR4& toString) { os << "(" << toString.v.x << ", " << toString.v.y << ", " << toString.v.z << ", " << toString.v.w << ")"; return os; } friend ostream& operator<<(ostream& os, const VECTOR2<TYPE>& toString); friend ostream& operator<<(ostream& os, const VECTOR3<TYPE>& toString); }; // Test code int main (int argc, char * const argv[]) { vec2 my2dVector(1, 2); cout << my2dVector.x << endl; cout << my2dVector.xx << endl; cout << my2dVector.xxx << endl; cout << my2dVector.xxxx << endl; vec3 my3dVector(3, 4, 5); cout << my3dVector.x << endl; cout << my3dVector.xx << endl; cout << my3dVector.xxx << endl; cout << my3dVector.xxxx << endl; vec4 my4dVector(6, 7, 8, 9); cout << my4dVector.x << endl; cout << my4dVector.xx << endl; cout << my4dVector.xxx << endl; cout << my4dVector.xxxx << endl; return 0; } The code WORKS and produces the correct output, but I prefer warning free code whenever possible. I followed the advice the compiler gave me (summarized here and described by forums and StackOverflow as the answer to this warning) and added the two things that supposedly tells the compiler what's going on. That is, I added the function definitions as non-friends after the predefinitions of the templated unions: template <typename TYPE> ostream& operator<<(ostream& os, const VECTOR2<TYPE>& toString); template <typename TYPE> ostream& operator<<(ostream& os, const VECTOR3<TYPE>& toString); template <typename TYPE> ostream& operator<<(ostream& os, const VECTOR4<TYPE>& toString); And, to each friend function that causes the issue, I added the <> after the function name, such as for VECTOR2's case: friend ostream& operator<< <> (ostream& os, const VECTOR3<TYPE>& toString); friend ostream& operator<< <> (ostream& os, const VECTOR4<TYPE>& toString); However, doing so leads to errors, such as: LINE 139: error: no match for 'operator<<' in 'std::cout << my2dVector.VECTOR2<float>::xxx' What's going on? Is it something related to how these templated union class-like structures are interrelated, or is it due to the unions themselves? Update After rethinking the issues involved and listening to the various suggestions of Potatoswatter, I found the final solution. Unlike just about every single cout overload example on the internet, I don't need access to the private member information, but can use the public interface to do what I wish. So, I make a non-friend overload functions that are inline for the swizzle parts that call the real friend overload functions. This bypasses the issues the compiler has with templated friend functions. I've added to the latest version of my project. It now works on both versions of GCC I tried with no warnings. The code in question looks like this: template <typename SWIZZLE> inline typename EnableIf< Is2D< typename SWIZZLE::PARENT >, ostream >::type& operator<<(ostream& os, const SWIZZLE& printVector) { os << (typename SWIZZLE::PARENT(printVector)); return os; } template <typename SWIZZLE> inline typename EnableIf< Is3D< typename SWIZZLE::PARENT >, ostream >::type& operator<<(ostream& os, const SWIZZLE& printVector) { os << (typename SWIZZLE::PARENT(printVector)); return os; } template <typename SWIZZLE> inline typename EnableIf< Is4D< typename SWIZZLE::PARENT >, ostream >::type& operator<<(ostream& os, const SWIZZLE& printVector) { os << (typename SWIZZLE::PARENT(printVector)); return os; }

    Read the article

  • How to get distinct values from the List&lt;T&gt; with LINQ

    - by Vincent Maverick Durano
    Recently I was working with data from a generic List<T> and one of my objectives is to get the distinct values that is found in the List. Consider that we have this simple class that holds the following properties: public class Product { public string Make { get; set; } public string Model { get; set; } }   Now in the page code behind we will create a list of product by doing the following: private List<Product> GetProducts() { List<Product> products = new List<Product>(); Product p = new Product(); p.Make = "Samsung"; p.Model = "Galaxy S 1"; products.Add(p); p = new Product(); p.Make = "Samsung"; p.Model = "Galaxy S 2"; products.Add(p); p = new Product(); p.Make = "Samsung"; p.Model = "Galaxy Note"; products.Add(p); p = new Product(); p.Make = "Apple"; p.Model = "iPhone 4"; products.Add(p); p = new Product(); p.Make = "Apple"; p.Model = "iPhone 4s"; products.Add(p); p = new Product(); p.Make = "HTC"; p.Model = "Sensation"; products.Add(p); p = new Product(); p.Make = "HTC"; p.Model = "Desire"; products.Add(p); p = new Product(); p.Make = "Nokia"; p.Model = "Some Model"; products.Add(p); p = new Product(); p.Make = "Nokia"; p.Model = "Some Model"; products.Add(p); p = new Product(); p.Make = "Sony Ericsson"; p.Model = "800i"; products.Add(p); p = new Product(); p.Make = "Sony Ericsson"; p.Model = "800i"; products.Add(p); return products; }   And then let’s bind the products to the GridView. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Gridview1.DataSource = GetProducts(); Gridview1.DataBind(); } }   Running the code will display something like this in the page: Now what I want is to get the distinct row values from the list. So what I did is to use the LINQ Distinct operator and unfortunately it doesn't work. In order for it work is you must use the overload method of the Distinct operator for you to get the desired results. So I’ve added this IEqualityComparer<T> class to compare values: class ProductComparer : IEqualityComparer<Product> { public bool Equals(Product x, Product y) { if (Object.ReferenceEquals(x, y)) return true; if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false; return x.Make == y.Make && x.Model == y.Model; } public int GetHashCode(Product product) { if (Object.ReferenceEquals(product, null)) return 0; int hashProductName = product.Make == null ? 0 : product.Make.GetHashCode(); int hashProductCode = product.Model.GetHashCode(); return hashProductName ^ hashProductCode; } }   After that you can then bind the GridView like this: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Gridview1.DataSource = GetProducts().Distinct(new ProductComparer()); Gridview1.DataBind(); } }   Running the page will give you the desired output below: As you notice, it now eliminates the duplicate rows in the GridView. Now what if we only want to get the distinct values for a certain field. For example I want to get the distinct “Make” values such as Samsung, Apple, HTC, Nokia and Sony Ericsson and populate them to a DropDownList control for filtering purposes. I was hoping the the Distinct operator has an overload that can compare values based on the property value like (GetProducts().Distinct(o => o.PropertyToCompare). But unfortunately it doesn’t provide that overload so what I did as a workaround is to use the GroupBy,Select and First LINQ query operators to achieve what I want. Here’s the code to get the distinct values of a certain field. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DropDownList1.DataSource = GetProducts().GroupBy(o => o.Make).Select(o => o.First()); DropDownList1.DataTextField = "Make"; DropDownList1.DataValueField = "Model"; DropDownList1.DataBind(); } } Running the code will display the following output below:   That’s it! I hope someone find this post useful!

    Read the article

  • How can I Setup overloaded method invocations in Moq?

    - by arootbeer
    I'm trying to mock a mapping interface IMapper: public interface IMapper<TFoo, TBar> { TBar Map(TFoo foo); TFoo Map(TBar bar); } In my test, I'm setting the mock mapper up to expect an invocation of each (around an NHibernate update operation): //... _mapperMock.Setup(m => m.Map(fooMock.Object)).Returns(barMock.Object); _mapperMock.Setup(m => m.Map(barMock.Object)).Returns(fooMock.Object); //... However, when the second Map invocation is made, the mapper mock throws because it is only expecting a single invocation. Watching the mapper mock during setup at runtime, I can look see the Map(TFoo foo) overload get registered, and then see it get replaced when the Map(TBar bar) overload is set up. Is this a problem with the way Moq handles setup, or is there a different syntax I need to use in this case?

    Read the article

  • Django automatically compress Model Field on save() and decompress when field is accessed

    - by Brian M. Hunt
    Given a Django model likeso: from django.db import models class MyModel(models.Model): textfield = models.TextField() How can one automatically compress textfield (e.g. with zlib) on save() and decompress it when the property textfield is accessed (i.e. not on load), with a workflow like this: m = MyModel() textfield = "Hello, world, how are you?" m.save() # compress textfield on save m.textfield # no decompression id = m.id() m = MyModel.get(pk=id) # textfield still compressed m.textfield # textfield decompressed I'd be inclined to think that you would overload MyModel.save, but I don't know the pattern for in-place modification of the element when saving. I also don't know the best way in Django to decompress when the field when it's accessed (overload __getattr__?). Or would a better way to do this be to have a custom field type? I'm certain I've seen an example of almost exactly this, but alas I've not been able to find it recently. Thank you for reading – and for any input you may be able to provide.

    Read the article

  • C# Nested Property Accessing overloading OR Sequential Operator Overloading

    - by Tim
    Hey, I've been searching around for a solution to a tricky problem we're having with our code base. To start, our code resembles the following: class User { int id; int accountId; Account account { get { return Account.Get(accountId); } } } class Account { int accountId; OnlinePresence Presence { get { return OnlinePresence.Get(accountId); } } public static Account Get(int accountId) { // hits a database and gets back our object. } } class OnlinePresence { int accountId; bool isOnline; public static OnlinePresence Get(int accountId) { // hits a database and gets back our object. } } What we're often doing in our code is trying to access the account Presence of a user by doing var presence = user.Account.Presence; The problem with this is that this is actually making two requests to the database. One to get the Account object, and then one to get the Presence object. We could easily knock this down to one request if we did the following : var presence = UserPresence.Get(user.id); This works, but sort of requires developers to have an understanding of the UserPresence class/methods that would be nice to eliminate. I've thought of a couple of cool ways to be able to handle this problem, and was wondering if anyone knows if these are possible, if there are other ways of handling this, or if we just need to think more as we're coding and do the UserPresence.Get instead of using properties. Overload nested accessors. It would be cool if inside the User class I could write some sort of "extension" that would say "any time a User object's Account property's Presence object is being accessed, do this instead". Overload the . operator with knowledge of what comes after. If I could somehow overload the . operator only in situations where the object on the right is also being "dotted" it would be great. Both of these seem like things that could be handled at compile time, but perhaps I'm missing something (would reflection make this difficult?). Am I looking at things completely incorrectly? Is there a way of enforcing this that removes the burden from the user of the business logic? Thanks! Tim

    Read the article

  • Challenge: Neater way of currying or partially applying C#4's string.Join

    - by Damian Powell
    Background I recently read that .NET 4's System.String class has a new overload of the Join method. This new overload takes a separator, and an IEnumerable<T> which allows arbitrary collections to be joined into a single string without the need to convert to an intermediate string array. Cool! That means I can now do this: var evenNums = Enumerable.Range(1, 100) .Where(i => i%2 == 0); var list = string.Join(",",evenNums); ...instead of this: var evenNums = Enumerable.Range(1, 100) .Where(i => i%2 == 0) .Select(i => i.ToString()) .ToArray(); var list = string.Join(",", evenNums); ...thus saving on a conversion of every item to a string, and then the allocation of an array. The Problem However, being a fan of the functional style of programming in general, and method chaining in C# in particular, I would prefer to be able to write something like this: var list = Enumerable.Range(1, 100) .Where(i => i%2 == 0) .string.Join(","); This is not legal C# though. The closest I've managed to get is this: var list = Enumerable.Range(1, 100) .Where(i => i%2 == 0) .ApplyTo( Functional.Curry<string, IEnumerable<object>, string> (string.Join)(",") ); ...using the following extension methods: public static class Functional { public static TRslt ApplyTo<TArg, TRslt>(this TArg arg, Func<TArg, TRslt> func) { return func(arg); } public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func) { Func<Func<T1, T2, TResult>, Func<T1, Func<T2, TResult>>> curried = f => x => y => f(x, y); return curried(func); } } This is quite verbose, requires explicit definition of the parameters and return type of the string.Join overload I want to use, and relies upon C#4's variance features because we are defining one of the arguments as IEnumerable rather than IEnumerable. The Challenge Can you find a neater way of achieving this using the method-chaining style of programming?

    Read the article

  • C# 4: conflicting overloaded methods with optional parameters

    - by Thomas
    I have two overloaded methods, one with an optional parameter. void foo(string a) { } void foo(string a, int b = 0) { } now I call: foo("abc"); interestingly the first overload is called. why not the second overload with optional value set to zero? To be honest, I would have expect the compiler to bring an error, at least a warning to avoid unintentional execution of the wrong method. What's the reason for this behaviour? Why did the C# team define it that way? Thanks for your opinions!

    Read the article

  • [C++] Can all/any struct assignment operator be Overloaded? (and specifically struct tm = sql::Resu

    - by Luke Mcneice
    Hi all, Generally, i was wondering if there was any exceptions of types that cant have thier assignment operator overloaded. Specifically, I'm wanting to overload the assignment operator of a tm struct, (time.h) so i can assign a sql::ResultSet to it. I have 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); //populating the struct 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

  • Singular method name for single object argument, plural for a list?

    - by nasufara
    I'm having a problem with naming a method for a database application. In my Database instance, I have a method that can remove an Agreement object from the database. However, I want to be able to remove multiple Agreements at once, to be able to use transactions. The problem is that I also have an overload to remove a single Agreement object. Essentially, my structure is like this: public class Database { // ... public void RemoveAgreement(Agreement a) { // ... } public void RemoveAgreement(IEnumerable<Agreement> agreements) { // ... } } But this can be confusing, as the overload with the list of Agreements has a singular name, despite being inherently plural. My question is, how should I structure this? Should I have two overloads with the name RemoveAgreement(), or RemoveAgreements()? Or should I use two separate methods, instead of overloads? Thanks.

    Read the article

  • Constructor Type Coercion in C++

    - by Robert Mason
    Take the following class: class mytype { double num; public: mytype(int a) { num = sqrt(a); } void print() { cout << num; } } Say there is a method which takes a mytype: void foo(mytype a) { a.print(); } Is it legal c++ (or is there a way to implement this) to call foo(4), which would (in theory) output 2? From what I can glean you can overload type casts from a user defined class, but not to. Can constructor do this in a standards-compliant manner (assuming, of course, the constructor is not explicit). Hopefully there is a way to in the end have this legal: int a; cin >> a; foo(a); Note: this is quite obviously not the actual issue, but just an example for posting purposes. I can't just overload the function because of inheritance and other program-specific issues.

    Read the article

  • Fast exchange of data between unmanaged code and managed code

    - by vizcaynot
    Hello: Without using p/invoke, from a C++/CLI I have succeeded in integrating various methods of a DLL library from a third party built in C. One of these methods retrieves information from a database and stores it in different structures. The C++/CLI program I wrote reads those structures and stores them in a List<, which is then returned to the corresponding reading and use of an application programmed completely in C#. I understand that the double handling of data (first, filling in several structures and then, filling all of these structures into a list<) may generate an unnecessary overload, at which point I wish C++/CLI had the keyword "yield". Depending on the above scenario, do you have recommendations to avoid or reduce this overload? Thanks.

    Read the article

  • Implementing default constructors

    - by James
    Implement the default constructor, the constructors with one and two int parameters. The one-parameter constructor should initialize the first member of the pair, the second member of the pair is to be 0. Overload binary operator + to add the pairs as follows: (a, b) + (c, d) = (a + c, b + d); Overload the - analogously. Overload the * on pairs ant int as follows: (a, b) * c = (a * c, b * c). Write a program to test all the member functions and overloaded operators in your class definition. You will also need to write accessor (get) functions for each member. The definition of the class Pairs: class Pairs { public: Pairs(); Pairs(int first, int second); Pairs(int first); // other members and friends friend istream& operator>> (istream&, Pair&); friend ostream& operator<< (ostream&, const Pair&); private: int f; int s; }; Self-Test Exercise #17: istream& operator (istream& ins, Pair& second) { char ch; ins ch; // discard init '(' ins second.f; ins ch; // discard comma ',' ins second.s; ins ch; // discard final '(' return ins; } ostream& operator<< (ostream& outs, const Pair& second) { outs << '('; outs << second.f; outs << ", " ;// I followed the Author's suggestion here. outs << second.s; outs << ")"; return outs; }

    Read the article

  • C++ union assignment, is there a good way to do this?

    - by Sqeaky
    I am working on a project with a library and I must work with unions. Specifically I am working with SDL and the SDL_Event union. I need to make copies of the SDL_Events, and I could find no good information on overloading assignment operators with unions. Provided that I can overload the assignment operator, should I manually sift through the union members and copy the pertinent members or can I simply come some members (this seems dangerous to me), or maybe just use memcpy() (this seems simple and fast, but slightly dangerous)? If I can't overload operators what would my best options be from there? I guess I could make new copies and pass around a bunch of pointers, but in this situation I would prefer not to do that. Any ideas welcome!

    Read the article

  • How does C++ free the memory when a constructor throws an exception and a custom new is used

    - by Joshua
    I see the following constructs: new X will free the memory if X constructor throws. operator new() can be overloaded. The canonical definition of an operator new overload is void *operator new(heap h) and the corrisponding operator delete. The most common operator new overload is pacement new, which is void *operator new(void *p) { return p; } You almost always cannot call delete on the pointer given to placement new. This leads to a single question. How is memory cleaned up when X constructor throws and an overloaded new is used?

    Read the article

  • C++ operator[] syntax.

    - by Lanissum
    Just a quick syntax question. I'm writing a map class (for school). If I define the following operator overload: template<typename Key, typename Val> class Map {... Val* operator[](Key k); What happens when a user writes: Map<int,int> myMap; map[10] = 3; Doing something like that will only overwrite a temporary copy of the [null] pointer at Key k. Is it even possible to do: map[10] = 3; printf("%i\n", map[10]); with the same operator overload?

    Read the article

  • C#/.NET Little Wonders: The Timeout static class

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. When I started the “Little Wonders” series, I really wanted to pay homage to parts of the .NET Framework that are often small but can help in big ways.  The item I have to discuss today really is a very small item in the .NET BCL, but once again I feel it can help make the intention of code much clearer and thus is worthy of note. The Problem - Magic numbers aren’t very readable or maintainable In my first Little Wonders Post (Five Little Wonders That Make Code Better) I mention the TimeSpan factory methods which, I feel, really help the readability of constructed TimeSpan instances. Just to quickly recap that discussion, ask yourself what the TimeSpan specified in each case below is 1: // Five minutes? Five Seconds? 2: var fiveWhat1 = new TimeSpan(0, 0, 5); 3: var fiveWhat2 = new TimeSpan(0, 0, 5, 0); 4: var fiveWhat3 = new TimeSpan(0, 0, 5, 0, 0); You’d think they’d all be the same unit of time, right?  After all, most overloads tend to tack additional arguments on the end.  But this is not the case with TimeSpan, where the constructor forms are:     TimeSpan(int hours, int minutes, int seconds);     TimeSpan(int days, int hours, int minutes, int seconds);     TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds); Notice how in the 4 and 5 parameter version we suddenly have the parameter days slipping in front of hours?  This can make reading constructors like those above much harder.  Fortunately, there are TimeSpan factory methods to help make your intention crystal clear: 1: // Ah! Much clearer! 2: var fiveSeconds = TimeSpan.FromSeconds(5); These are great because they remove all ambiguity from the reader!  So in short, magic numbers in constructors and methods can be ambiguous, and anything we can do to clean up the intention of the developer will make the code much easier to read and maintain. Timeout – Readable identifiers for infinite timeout values In a similar way to TimeSpan, let’s consider specifying timeouts for some of .NET’s (or our own) many methods that allow you to specify timeout periods. For example, in the TPL Task class, there is a family of Wait() methods that can take TimeSpan or int for timeouts.  Typically, if you want to specify an infinite timeout, you’d just call the version that doesn’t take a timeout parameter at all: 1: myTask.Wait(); // infinite wait But there are versions that take the int or TimeSpan for timeout as well: 1: // Wait for 100 ms 2: myTask.Wait(100); 3:  4: // Wait for 5 seconds 5: myTask.Wait(TimeSpan.FromSeconds(5); Now, if we want to specify an infinite timeout to wait on the Task, we could pass –1 (or a TimeSpan set to –1 ms), which what the .NET BCL methods with timeouts use to represent an infinite timeout: 1: // Also infinite timeouts, but harder to read/maintain 2: myTask.Wait(-1); 3: myTask.Wait(TimeSpan.FromMilliseconds(-1)); However, these are not as readable or maintainable.  If you were writing this code, you might make the mistake of thinking 0 or int.MaxValue was an infinite timeout, and you’d be incorrect.  Also, reading the code above it isn’t as clear that –1 is infinite unless you happen to know that is the specified behavior. To make the code like this easier to read and maintain, there is a static class called Timeout in the System.Threading namespace which contains definition for infinite timeouts specified as both int and TimeSpan forms: Timeout.Infinite An integer constant with a value of –1 Timeout.InfiniteTimeSpan A static readonly TimeSpan which represents –1 ms (only available in .NET 4.5+) This makes our calls to Task.Wait() (or any other calls with timeouts) much more clear: 1: // intention to wait indefinitely is quite clear now 2: myTask.Wait(Timeout.Infinite); 3: myTask.Wait(Timeout.InfiniteTimeSpan); But wait, you may say, why would we care at all?  Why not use the version of Wait() that takes no arguments?  Good question!  When you’re directly calling the method with an infinite timeout that’s what you’d most likely do, but what if you are just passing along a timeout specified by a caller from higher up?  Or perhaps storing a timeout value from a configuration file, and want to default it to infinite? For example, perhaps you are designing a communications module and want to be able to shutdown gracefully, but if you can’t gracefully finish in a specified amount of time you want to force the connection closed.  You could create a Shutdown() method in your class, and take a TimeSpan or an int for the amount of time to wait for a clean shutdown – perhaps waiting for client to acknowledge – before terminating the connection.  So, assume we had a pub/sub system with a class to broadcast messages: 1: // Some class to broadcast messages to connected clients 2: public class Broadcaster 3: { 4: // ... 5:  6: // Shutdown connection to clients, wait for ack back from clients 7: // until all acks received or timeout, whichever happens first 8: public void Shutdown(int timeout) 9: { 10: // Kick off a task here to send shutdown request to clients and wait 11: // for the task to finish below for the specified time... 12:  13: if (!shutdownTask.Wait(timeout)) 14: { 15: // If Wait() returns false, we timed out and task 16: // did not join in time. 17: } 18: } 19: } We could even add an overload to allow us to use TimeSpan instead of int, to give our callers the flexibility to specify timeouts either way: 1: // overload to allow them to specify Timeout in TimeSpan, would 2: // just call the int version passing in the TotalMilliseconds... 3: public void Shutdown(TimeSpan timeout) 4: { 5: Shutdown(timeout.TotalMilliseconds); 6: } Notice in case of this class, we don’t assume the caller wants infinite timeouts, we choose to rely on them to tell us how long to wait.  So now, if they choose an infinite timeout, they could use the –1, which is more cryptic, or use Timeout class to make the intention clear: 1: // shutdown the broadcaster, waiting until all clients ack back 2: // without timing out. 3: myBroadcaster.Shutdown(Timeout.Infinite); We could even add a default argument using the int parameter version so that specifying no arguments to Shutdown() assumes an infinite timeout: 1: // Modified original Shutdown() method to add a default of 2: // Timeout.Infinite, works because Timeout.Infinite is a compile 3: // time constant. 4: public void Shutdown(int timeout = Timeout.Infinite) 5: { 6: // same code as before 7: } Note that you can’t default the ShutDown(TimeSpan) overload with Timeout.InfiniteTimeSpan since it is not a compile-time constant.  The only acceptable default for a TimeSpan parameter would be default(TimeSpan) which is zero milliseconds, which specified no wait, not infinite wait. Summary While Timeout.Infinite and Timeout.InfiniteTimeSpan are not earth-shattering classes in terms of functionality, they do give you very handy and readable constant values that you can use in your programs to help increase readability and maintainability when specifying infinite timeouts for various timeouts in the BCL and your own applications. Technorati Tags: C#,CSharp,.NET,Little Wonders,Timeout,Task

    Read the article

  • Are You Drowning in E-mail ?

    Learn to Reduce Email Overload By 54% E-mail is Making You Stupid! At least, that';s what a headline in the March edition of Entrepreneur Magazine claims. But that';s not all... a survey from the Radi... [Author: Ted Gulas - Computers and Internet - June 07, 2010]

    Read the article

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