c++,templates,overloading,return-type,specialization
It's not an overload, it's a specialization. They are different mechanisms (in fact mixing the two can lead to confusion, because overloads are resolved before specializations are considered -- see this Sutter's Mill article for example: http://www.gotw.ca/publications/mill17.htm).
c++,templates,overloading,return-type
You can use decltype() for this, using std::declval to simulate values of the types needed to create the method call expression: typename R = decltype(std::declval<X>().f(std::declval<T&>())) Here is a demo that outputs the type ID of R; you can see that it correctly deduces double and int * for ff(a) and...
c++,inheritance,polymorphism,overloading
I believe the idea is that if you don't override Draw in IsoscelesTriangle (and changing the signature is not overriding anymore), you end up with 2 Draw functions in the final class IsoscelesTriangle, one from IsoscelesPolygon and other from Triangle, and both try to override the Draw from Polygon. The...
c++,vector,overloading,operator-keyword
template <typename T> std::istream& operator>>(std::istream& is, std::vector<T>& v) { std::copy(std::istream_iterator<T>(is), std::istream_iterator<T>(), std::back_inserter(v)); return is; } ...
c++,string,operator-overloading,overloading
I don't know why you are trying to reinvent the wheel, there is already append method which do the same thing you are trying to do. Don't forget that string is not a primitive type in C++ it's an object. For your problem, it seems that the cast (string)ex is...
There is no problem in overloading a method inside interface An interface is a contract that is mandatory for implementing classes to implement. If you do not want classes to implement that method. There is no need to include it in interface as well. So you can write that...
You can make all your methods have different names. The point is you don't have to. This reduces the number of names a developer using the API needs to learn. e.g. in the PrintWriter you have lots of methods called print and println which conceptually all do the same thing....
oracle,stored-procedures,overloading
It's because of the IN VARCHAR2 := NULL declaration; you're providing a default value for the parameter, making it optional. When you have a call like ERR.Log_And_Return; you could be calling your first version that takes no arguments, or calling your second version that has an argument but letting it...
You need #include <iostream> Or at least #include <ostream> 2 other advises: the include guards (ifndef, define and endif) should be at the very beginning and at the very end of the header file (the endif MUST NOT be in the source file, but in the header file) Adding using...
namespace A { struct Foo{}; } namespace B { struct Bar{}; } namespace A { int operator+(const A::Foo&, const B::Bar&); } namespace B { char operator+(const A::Foo&, const B::Bar&); } int main() { A::Foo() + B::Bar(); } ADL finds both A::operator+() and B::operator+(). The two signatures are different only in...
Run javah on your Java file declaring the native methods and you will see that you need two different Java_com_xxx functions. The C-level declarations must be unique.
You may change your macro to return an object with operator ()(const std::string&), something like: struct Logger2 { explicit Logger2(const std::string& name) : name(name) {} Logger2& operator << (const std::pair<const char*, const char*>& p) { std::cout << name << ":" << p.first << " " << p.second << std::endl; return...
java,function,generics,java-8,overloading
The example you present in your question has got nothing to do with Java 8 and everything to do with how generics work in Java. Function<T, Integer> function and Function<T, Double> function will go through type-erasure when compiled and will be transformed to Function. The rule of thumb for method...
c++,templates,c++11,overloading,argument-dependent-lookup
Explicit function template specializations never change which function template or overload is called, only the implementation of the template if it is called. Overload resolution ignore specializations (as opposed to overloads, which can look a lot like partial specialization to someone unfamiliar with C++ function template quirks). I can imagine...
java,math,double,overloading,area
What you have to do is give your area() method an input variable that is the radius Like so: public static double area(double radius) { //same as before double areaCircle; double powRadius; powRadius = Math.pow(radius, 2); areaCircle = (Math.PI *(powRadius)); return areaCircle; } Also rename your other area() method. As...
But "A function pointer is not a class type" is the correct answer. There's the following note in clause 13.6: operator overload resolution occurs only when an operand expression originally has class or enumeration type The normative rule is in 13.3.1.2 (emphasis mine): If no operand of an operator in...
The constructor template from error_code is indeed considered in overload resolution - you correctly specialized is_error_code. The problem is the ADL in this line in the definition of error_codes constructor template: *this = make_error_code(__e); ADL does not consider the global namespace because X was only defined in NS, not the...
c++,linked-list,overloading,assignment-operator
The this pointer is unavailable because your function signature does not resemble a member definition, you're missing the type scope resolution part of the signature: template <class T> SortedLinkList<T>& operator=(const SortedLinkList<T> & otherList) should be: template <class T> SortedLinkList<T>& SortedLinkList<T>::operator=(const SortedLinkList<T> & otherList) ...
When you use override, you're saying that you're overriding the virtual method with the same signature inherited from a parent class. If the parent class doesn't have a virtual method with that signature, then the compiler will rightly complain that it can't find it. Check the ancestor classes to confirm...
Usually you'd either define two different functions, or do something like: def foo(x, y = None): if y is None: x, y = x.x, x.y # do something at position (x, y) The option to define two different functions seems unwieldy if you're used to languages that have overloading, but...
There is no += function. It is simply syntactic sugar for a = a + b. It is also not mutating. So a += b calculates a + b and then changes a to refer to the result. This means there is memory allocation for the result of a +...
c++,templates,overloading,derived-class
If you change this: void Process(std::string) {} to this: void Process(int) {} your code will compile. This is a strong tip on why my code doesn't compile. Let's see what's happening here: We have: Derived() { BaseWrapper * wrap = new Wrapper<Derived>(this); } which will call the constructor of Wrapper...
haskell,polymorphism,overloading,typeclass
The problem you're facing is that the overloading is determined by all of the types in the class—including ones that only appear as return types. You could have instances for both MyClass Bool Int and MyClass Bool String, and it would be able to disambiguate based on what type is...
The difference is the extern "C", which affects namespace membership of the function: From http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1997/N1138.pdf What remains is the definition of “same entity” with respect to ‘extern “C”’ language linkage? This is addressed by 7.5¶6: “At most one function with a particular name can have C language linkage. Two declarations...
c++,templates,c++11,constructor,overloading
I presume this is because T&& is a universal reference ... Incorrect. T&& is not a universal (forwarding) reference in this case. T&& is exactly an rvalue reference to T. Universal/forwarding references must be deduced. ... and due to reference collapsing rules, the second constructor also gets converted to...
c++,templates,c++11,overloading,typetraits
The problem is this: proxy(foo, 5); The compiler tries to deduce the type of foo, but there are 2 overloads. Of course, it can deduce Args... from 5, but the type of foo is still non-deducible, since the compiler doesn't know which overload to pick when doing the type deduction....
You probably want to change RewrittenObservable as follows: public abstract class RewrittenObservable { // ... public void <T extends Event> notify(T event) { observer.update(this, event); } } Be aware that this may not work with the current Structure of RewrittenObserver, because the overloading is possibly ambiguous. You probably want a...
So, I'm guessing it's because your signatures don't match. You have: friend numbers operator+(numbers firstFraction, numbers secondFraction); friend istream& operator >>(istream& in, numbers& fraction); friend ostream& operator<< (ostream& out, numbers fraction); But your actual functions are: numbers operator+(numbers &firstFraction, numbers &secondFraction) // BAD istream& operator >> (istream &in, numbers &fraction)...
c++,qt,overloading,shared-ptr,qhash
Speak of the devil, and he doth appear: https://codereview.qt-project.org/113340 This cannot simply be something the Qt developers overlooked. It's not an overlook, it's just that Qt doesn't have endless resources to add qHash overloads to any STL type which has an operator==....
javascript,function,methods,overloading
fn.length will return the number of parameters defined in fn. Will arguments.length return the number of which arguments? The already existing function's? No. arguments is an array-like local variable that's available inside of a function. It contains the number of arguments passed to the function. The rest of your...
macros,polymorphism,scheme,overloading
I think that Chris is right in that this is not really a job for macros. A simple procedure might be what you're looking for: (define (lookup key container) (cond ((type1? container) (type1-lookup key container)) . ; repeat for whichever types.. . ((typeN? container) (typeN-lookup key container)) (else 'undefined-lookup))) ;...
java,polymorphism,overloading,overriding
The problem is that the method signature to be called is chosen at compile time. The compiler only knows that parent is of type Parent, so the only compatible signature is add(double, double), because both longs can be widened to be doubles. The Child method add(long, long) is an overload,...
c++,overloading,c++14,inheriting-constructors
I can't tell you the rationale for this, but I can at least tell you that it is standard-mandated: [C++11: 12.9/3]: For each non-template constructor in the candidate set of inherited constructors other than a constructor having no parameters or a copy/move constructor having a single parameter, a constructor is...
c++,templates,operator-overloading,overloading,overload-resolution
After template argument deduction, the second version becomes a perfect match: template <typename U> void operator+= (const U& rhs); // U = mDcmImage<int> compared to the first version, which requires a conversion from mDcmImage to mArray: template <typename U> void operator+= (const mArray<U>& other); // U = int so it...
c++,constructor,overloading,friend
You can't add constructors (or other members) to a class. However, you can create a conversion operator in the other class involved: class B { // ... public: explicit operator A() const { /* build an A object and return it */ } }; ...
c#,arrays,operators,overloading
You can create an implicit operator like this: public class Point3 { public static implicit operator Point3(int[] ints) { return new Point3(); } } Which can be invoked using this: Point3 p1 = new[] { 1, 2, 3 }; Note that you explicitly need to create the array and can't...
php,oop,reference,dependencies,overloading
The way you're doing this is confusing. What works best is injection. In other words, I would skip the overloading entirely and define your database class outside your other classes and then inject them into your constructor. That way you only define your database connection once and save overhead. $db...
From Standard §13.1 Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. That is, the const and volatile type-specifiers for each parameter type are ignored when determining which function is being declared, defined, or called. [ Example: typedef const int cInt; int f...
javascript,dart,operator-overloading,operators,overloading
Operators are just syntactic sugar for method calls and there is nothing special to consider for dart2js.
The thing that you are missing is that the return type of a method is not part of its signature. The definition of override-equivalent in 8.4.2 says: "Two methods have the same signature if they have the same name and argument types." Note that there is no mention of return...
python,c++,dynamic,overloading
Polymorphism in C++ relies on pointers. If you have a base class Poly and then child classes Polya, Polyb, Polyi.. etc. you can have a Poly* actually pointing to a Polya*, however you cannot have a Poly containing a Polya because you will face type-slicing. So you can have something...
c++,overloading,function-overloading
Two choices: either extract common functionality into its own function (refactoring), or have one call the other. In your case, you can define the first overload like this: bool bar::foo(unsigned arg) { return foo(arg, _timeout); } In general, refactoring is also a good approach: void bar::foo_inner(unsigned arg) { // or...
Inside your for loop, you are indexing v.m_pBuf based on i where you are skipping all odd i. Thus you are trying to acess locations 0, 2, 4, ... which implies you are going past your allocated space. Try using a different index variable and increment it inside the if...
It doesn't work as a member function because your F2 alternative takes a jVector as the first operand ALWAYS (it is a member function, so you don't have a choice of what the first argument is - it is jVector *this [hidden by the language]). The compiler could in theory...
c++,c++11,design-patterns,overloading,shared-ptr
This is not how std::shared_ptr works. You are creating your instances of ParticleEmitter on the stack, but std::shared_ptr is used to manage instances which are created on the heap. In your code, when you add a new emitter to the ParticleManager, and wrap it into a shared pointer, the emitter...
wcf,rest,methods,overloading,fiddler
Try changing the uri template: [WebInvoke(uriTemplate="/StrDetails?str1={str1}&str2={str2}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] ...
Yes, it is possible using CRTP: #include <iostream> class AbstractElement; class ConcreteElement; class SuperConcreteElement; class B { public: void bar(AbstractElement*) { std::cout << "Abstract element" << std::endl; } void bar(ConcreteElement*) { std::cout << "Concrete element" << std::endl; } void bar(SuperConcreteElement*) { std::cout << "Super concrete element" << std::endl; } };...
c++,c++11,polymorphism,overloading,final
This declaration in class B void foo(int b) override { std::cout << b; } hides all other functions with the same name declared in class A (excluding of course the overriden function). You can either call the function explicitly like this b->A::foo(); Or include using declaration using A::foo; in the...
c++,templates,c++11,overloading,explicit-specialization
You can extend the idea of a helper template class, and put pretty much everything in there. It's not exactly pretty for whoever has to write the specialisations, but it's very convenient for the user, who can just call f<0>, f<1>, etc. It doesn't really need decltype, but decltype does...
c#,oop,inheritance,overloading
Your m2.PrintName just returns the string it receives. It doesn't do anything with it. If you do so, you will see output. public string PrintName(String strPolymorphism) { this.PrintName(); // first write the output of `PrintName` to the console Console.WriteLine("Called PrintName with: " + strPolymorphism); return strPolymorphism; } Your overload m2.PrintName...
c++,pointers,reference,overloading
There should be only one way to do a specific thing. This will make the code clearer for its users. Therefore, you should pick only one, depending on the semantics: If a nullptr is a meaningful value to be passed to createFoo, then declare the function to take a pointer....
java,overloading,definition,method-overloading
As Java is statically typed language, the result of the ternary operator must have an explicit type, defined during the compilation, so the compilator can continue handling the outer expression. As the both branches of ternary are numbers, they are promoted to the more precise type as described in JLS...
5.5 is a double, but none of your functions take a double argument. So, the compiler gets confused on whether to call the function with the int parameter, or the function with the float parameter. So, you get a an error saying it is ambiguous. That is why when you...
c++,qt,inheritance,overloading,operator-keyword
As I eventually realised above, this isn't possible. The operator ->() has to return the type upon which it is acting, and for that reason it can't be used as a virtual function.
Overload resolution uses the static types (not that it would make a difference here). So both b->function() and b->function( s ) resolve to Base::function, with no error. Finally, since these functions have been declared virtual, the final resolution will take into account any overloads in a derived class. But there...
interface,typescript,overloading
This should probably avoid compiler errors since you tell explicitly TS: labelGenerators[0] = <ILabelGenerator>( (container: SomeContainerObject, x: number, y: number) => { return "label 0"; //the real code uses the parameters }); ...
The most specific function definition will be called. int a, int b, int c is more specific than int... c. For the same reason the following is valid static void foo(String a) { } static void foo(Object a) { } and the first would be called for foo("bar"); Further reading...
c++,templates,overloading,c++14,template-specialization
Simplest way would be something like template<class T, bool = std::is_class<T>::value> class Io:public T,public Io_obj { /* ... */ }; template<class T> class Io<T, false> : public Io_obj { /* ... */ }; If the two specializations share a substantial amount of code, you may want to put it in...
I think you can implement this by using functor and take the comparator(operator< overload) outside the AttSet. Here is a simple example: struct AtrComparator { bool distcmp; AttrComparator(bool distcmp): distcmp(distcmp) {} bool operator() (const AttSet &s1, const AttSet &s2) { if(distcmp) { return s1.dist < s2.dist; } else { return...
vb.net,linq,dictionary,overloading
You need to use AsEnumerable() (see the Remarks section) to pick up the extension methods when the names clash. data.AsEnumerable().Count(Function(x) x.Value > 0) ...
c++,dictionary,containers,overloading,ostream
Your operator<< for stack is popping all of the elements off of the stack, so the stack is empty by the time you make a copy of it to put in the map. To demonstrate, if I change your main() to this: int main() { stack<int> s2; s2.push(1); s2.push(2); cout...
No, C doesn't support function overloading. The POSIX open function is actually a variadic function, its signature is: int open(const char *path, int oflag, ... ); ...
Overloading must be resolved at compile time as it might be ambiguous to resolve the method dispatch at runtime. Imagine the following snippet (valid and compilable Java program): public class Test { public static void main(String[] args) { Object object = new Clazz(); method(object); } static class Clazz implements Interface1,...
c++,templates,overloading,template-specialization
First of all, according to the standard (start of §13): “When two or more different declarations are specified for a single name in the same scope, that name is said to be overloaded.[...]Only function and function template declarations can be overloaded; variable and type declarations cannot be overloaded.” So clearly,...
java,oop,overloading,type-promotion
Java Code You have to pass an object for it to take object verion public class TestProgram { public void method(Object o) { System.out.println("Object Verion"); } public void method(String s) { System.out.println("String Version"); } public static void main(String args[]) { TestProgram question = new TestProgram(); question.method(question); } } ...
c++,function,templates,object,overloading
You are calling your function with two different parameters but your function is templated to one type template<class T6> bool checkPosition( const T6 &object1, const std::vector<T6> &object2 ); Means that that you want an object and a vector of objects of the same type. You are passing into the function...
c++,overloading,operator-keyword
You should implement solution 1. When in doubt, just look at what's already being done. As you can see below, the fail bit is being set if we try to read from a stream in EOF state. Note that EOF is not the only way to fail though. Try setting...
This happens because the compiler will prefer built-in conversions to user-defined conversions. The conversion from a pointer to a bool is built-in, so that overload is selected rather than constructing a std::string. You could add an overload which takes a const char* and forwards it to the std::string version: void...
java,inheritance,polymorphism,overloading,overriding
If the method Edit is in fact different for every kind of derived class and you must check what kind of class the object in the list is (and you do that in if (animals.get(i) instanceof Dog){...}) then that means your method is not generic = not applicable for all...
c++,templates,hashtable,overloading
"But I've never heard of "Class Overloading". What is the right way to solve this problem do you think?" You might use a template class and specializations (overloads) for it's interface: template<typename T> class hash_table { public: bool probe(const T& x); hash_table<T> chain(const T& x); }; template<> bool hash_table<int>::probe(const...
For class methods, the this part is considered as if it were an extra argument. So if you made the CString one const, that makes the overload set: Comparison(const TestBed&, CString const&) // (1) Comparison(TestBed&, std::string const&) // (2) For (1), we need to do two conversions: a const conversion,...
c#,type-conversion,overloading
Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes. Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required when...
new Employee(); is invoking public Employee(){ this("JJ", 0); System.out.println(name +" "+ idNumber); } In this constructor this("JJ", 0); is invoking public Employee(String name, int num) constructor, which ends with call System.out.println(name +" 2nd "+ idNumber);. which is responsible for printing JJ 2nd 0 When this("JJ", 0); will finish System.out.println(name +"...
The issue is your operator << outputs the amount member. However it is uninitialized: // Define the output operator ostream& operator<<(ostream& outputStream, const Money& money) { outputStream << money.amount; // not initialized return outputStream; } If you look at your cout in main, you have this: (m7 + m8) This...
java,inheritance,parameters,override,overloading
In my opinion it would be better to do like this: public class LotteryTicket { protected int pickAmount; protected boolean isRandom; protected List<Integer> numbersPicked; protected Date datePurchased; protected SimpleDateFormat sdf; protected int[] numbersToPick; //To create random valued ticket public LotteryTicket(int pickAmount) { this.pickAmount = pickAmount; isRandom = true; } //To...
The Java Language Specification says this about method signature resolution: The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase. In your second...
c++,polymorphism,overloading,function-overloading
Option 1 You could use a template for your call function. #include <iostream> class A {}; class B : public A {}; void fun(A v) { std::cout << "A" << std::endl; } void fun(B v) { std::cout << "B" << std::endl; } template <typename T> void call(T v) { fun(v);...
c++,templates,overloading,heap-corruption
You have a mistake in your copy constructor: elements = new T(numOfElem); It should be elements = new T[numOfElem]; By writing new T(numOfElem); you allocate only one variable with its value initialized to numOfEllem. Use a std::vector instead of the array and you will avoid such problems. Your code is...
python,c++,boost,static,overloading
I believe this line: .def("method", (int(C::*)(const std::string&, int, bool))0, method1()) should look like this: .def("method", &C::method, method1()) And you should use BOOST_PYTHON_FUNCTION_OVERLOADS instead of BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS, since there's no C object involved (static function pointers are just function pointers, they're not pointer-to-members). There is also an example posted on this wiki...
The problem is that in typename test1<T>::test2, template parameter T is in a non-deduced context, so C++ can not deduce its template argument from the types of the function arguments. You can see this by explicitly instantiating the function template: test1<int>::test2 flags = operator | <int> (test1<int>::test3, test1<int>::test4); DEMO Or...
You can overload the division operator, but: It must always be a binary operator - you've only provider one operand It must always be static At least one of the operand types must be the type you're declaring it in So for example: using System; class Program { public static...
c++,operators,overloading,precedence
OK so let's simplify and break down what's going on here. The first part of your call evaluates to something like this: myClass << 12 << myClass(array,10) becomes myClass.operator<<(12).operator<<(myClass(array, 12) which when notionally spelling out the implicit this parameter becomes something like operator<<(operator<<(myClass, 12), myClass(array, 10)) Now the only thing...
matlab,size,overloading,operator-keyword
As mentioned in comments by patrik use varargout... With the addition of nargout the size method can be implemented as follows: function varargout = size(this,varargin) [varargout{1:nargout}] = builtin('size',this.val,varargin{:}); end As a side note due to the possible corner case of val having a class using an overloaded size method the...
c++,overloading,operator-keyword
IF, and only if, you have all the information you need to determine the equality, it is no problem to define the function yourself: //not sure what GdkColor contains, but if it is large pass by const & bool operator==(GdkColor a, GdkColor b) { //check equality here return result; }...
python,string,class,python-2.7,overloading
This is exactly what the __new__ method is for. In Python, creating an object actually has two steps. In pseudocode: value = the_class.__new__(the_class, *args, **kwargs) if isinstance(value, the_class): value.__init__(*args, **kwargs) The two steps are called construction and initialization. Most types don't need anything fancy in construction, so they can just...
c#,oop,namespaces,overloading,terminology
Overloading happens when you have multiple methods in the current class that have the same name but different signature. The scope of method overloading is "Within the current class" public class Math2 { // This one's for squares public static double Area(double side) { return side * side; } //...
c++,const,overloading,operator-keyword
Because for user-defined conversions with a conversion operator the conversion of the returned type to the destination type (i.e. char* to bool) is considered after the object argument conversion, i.e. the conversion of the object argument a to the implicit object parameter. [over.match.best]/1: Given these definitions, a viable function F1...
c++,templates,overloading,function-overloading,overload-resolution
Overload resolution occurs in the following steps: A set of candidate functions is assembled. This set of candidates consists of both non-template functions and specializations of function templates. If template parameter deduction fails on a function template, it's silently removed from the set of candidates. A subset of candidate functions...
c++,overloading,operator-keyword,stdvector
You said: But I want to add kind of type checking to implementation so that this + operation will be invoked only about numerical types(eg. int, double...). You can add a static_assert. template <typename T> std::vector<T> operator+(std::vector<T> v1, const std::vector<T>& v2) { static_assert(std::is_arithmetic<T>::value, "Need arithmetic type"); ...
No, this is not directly possible in C++ AFAIK, but you can use double dispatch to achieve your desired result. class GenericMove; class SwapMove; class SoftConstraint { public: virtual int evaluate(GenericMove& move) = 0; virtual int evaluate(SwapMove& move) = 0; }; class M1 : public SoftConstraint { public: int evaluate(GenericMove&...
c++,class,operator-overloading,overloading
You don't have a default constructor so when it tries to construct Soma you get an error. Once you provide your own constructor the default one provided by the compiler is no longer generated. You either have to make your own or add default values to the parameters on the...
c++,templates,c++11,overloading,va-list
Force type construction: log(std::string{"hello}). But this isn't really what you seem to want. In either of the functions, call the other one. void log(const string& s) { log(s.c_str()); } But it's not very efficient because you'll have a useless string object, although the compiler may be able to inline...
Your output operator<< should accept the stream as the first argument, and the fraction as the second argument. Right now, it does the opposite (the fraction is the first argument, and the stream is the second). This means the operator isn't called, instead the fraction is converted to float and...
out and ref are considered part of the method signature. From $3.6 Signatures and overloading; Note that any ref and out parameter modifiers (Section 10.5.1) are part of a signature. Thus, F(int) and F(ref int) are unique signatures. Your second example, c is optional argument. Even if you call without...
arrays,class,constructor,operators,overloading
I would answer your first question and would like you to inquire more on how would you approach to the second problem. Until and unless you work through the compilation issues, you won't get that vision that you need to approach any other computer problem. In the below code, `Array(int...