C++ :: Overload With Template Function

Nov 15, 2013

I am a beginner, got confused about:

template<typename T> int compare(T &a,T &b);
int compare(const char *a,const char *b);
char ch_arr1[6]="world",ch_arr2[6]="hello";
compare(ch_arr1,ch_arr2);

After running the code above,we got to know the non-template function is called. What I know is that the array arguments ch_arr1,ch_arr2 will not be converted to char * because the parameters are references in the template functions.

ch_arr1,ch_arr2 need to be converted to const char * if compare(const char *a,const char *b) were called.

I just wanna know what exactly happened behind that? and why?

View 15 Replies


ADVERTISEMENT

C++ :: Overload Template Function In A Class?

Jun 21, 2013

Firstly, is it legal to overload a template function in a class? This is what I did

class FILE_txt
{
public:
FILE_txt(const char* );

[Code]....

View 19 Replies View Related

C++ :: Possible To Overload A Class For Passing To A Function

Feb 1, 2014

I want to be able to do

someFunction(MyObject)

rather than

someFunction(MyObject.getWhatIWant())

I know I can do &MyObject, MyObject() and MyObject[0] by overloading operators but is it possible with just plain old MyObject?

this is assuming that I have no access to someFunction(), i.e, it cannot be modified.

View 7 Replies View Related

C++ :: Define To Overload Virtual Function

Jul 11, 2014

I want to overload pure virtual function from 3rd party SDK class to put my debug messages like that:

errorStatus aXsaction(){printf(_T("
abort transaction"));transactionManager->abortTransaction();}

#define transactionManager->abortTransaction() aXsaction()

But compiler complains on the minus sign:
error C2008: '-' : unexpected in macro definition

Is it possible to trick the compiler?

View 4 Replies View Related

C++ :: Dealing With Operator Overload Function Failure

Aug 23, 2014

Say I have a class that requires dynamic allocation to implement a few of the operators. Take "+" for example; I need to create a new object to hold the sum of the two parameters whose size is not known at compile time.

I'm pretty sure the standard way to indicate a failure inside the overloading function would be to throw an exception. However I am currently involved in an embedded(ish) project where the spec. says no exceptions are to be used.

I think I have 2 options:

1. Return an "invalid" object (with a flag indicating an error has occurred) and check for this after each operation.

a = b + c
if (a.err)
// handle error
or

2. To forsake operator overloading entirely and think up a new way of doing things where all functions that involve dynamic allocation can return error codes. but this seems rather terrible too as I may end up with something like:

objA a
if (add(&a, b, c) == -1) // assuming b and c are initialized before this snippet starts
// handle error

Is there a number 3 that I haven't thought of? It seems that not allowing exceptions is fairly common even in the non-embedded world [URL] so how is this normally done? or is operator overloading usually avoided when exceptions are not allowed?

View 3 Replies View Related

C++ :: Overload Virtual Member Function In Polymorphism?

Nov 30, 2013

I defined a virtual class and three other classes based on it. I want to use them like this:

int main() {
Dirichlet_t D;
Neumann_t N;
Cauchy_t C;

PDEBoundary_t * B1=& D;
PDEBoundary_t * B2=& N;
PDEBoundary_t * B3=& C;

[Code] .....

but I got two major errors
1: "object f abstract type is not allowed" error.-----why not?
2: "the derived class must implement the inherited pure virtual method"-----Did't I?

View 15 Replies View Related

C/C++ :: Overload Operator With Friend Function Using Constructors

Dec 26, 2014

I want to overload prefix and postfix increment(++) operators with friend function. I also have to use the constructors for this. How can I do this? in C++

View 4 Replies View Related

C++ ::  how To Declare Template Function Inside Template Class

Dec 5, 2013

I'm trying to implement a simple template array class, but when i came into the operator< i actually have to use a template :

my code is something like :

template<typename _Type, std::size_t _Size>
class array {
public :

[Code] ......

but i am having an error of shadows template param 'class _Type' is it w/ the name conflict between the array template parameter and the function template parameter ?

View 6 Replies View Related

C++ :: Write Prototype Of A Member Function To Overload Insertion Operator

Apr 10, 2014

Consider the class specification below. Write the prototype (i.e. header) of a member function to overload the insertion operator (i.e. <<). The << operator is to output the data members of an instance of class StudentTestScores into an output stream. Your definition should allow for chaining of output operations (e.g. cout << x << y; where x and y are of type StduentTestScires).

#include <string>
using namespace std;
class StudentTestScores{
private:
string studentName;
float *testScores; // used to point to an array of test scores
int numTestScores; // number of test scores

[code]....

View 1 Replies View Related

C++ ::  Writing A Function Template With Template Arguments?

Mar 14, 2014

I have a function:

template<class Iterator, class T>
void a(Iterator, Iterator, const T&);

and I want to be able to simplify calls to 'a' with calls like

a(someIteratableContainer);

instead of having to call:

a(someIteratableContainer.begin(), someIteratableContainer.end(), valueOfTheContainersElementType);

I also want to be able to generalize the function to handle any of the standard iteratable contains: array, vector, deque, whatever.

I was under the impression I could write:

template<template<class T> class U> a(U<T>& container) {
a(container.begin(), container.end(), g(T()));
}

where 'g()' returns an object of the element type. However, the compiler is claiming, no matter how I write a call to the overload, the original template is selected and/or the overload is invalid, depending on the various ways I attempt to write said overload.

View 7 Replies View Related

Visual C++ :: Circular Buffer - No Instance Of Overload Function Matches Argument List

Nov 25, 2014

I'm having some issues with my code. For the produce function i am getting an error saying 'no instance of overload function produce() matches the argument list' and also for the lines buffer[head].data = message; buffer[head].time = current_time i get an error saying 'expression must have pointer to object type.

In the code i'm not sure if i passed the variables to the function correctly. I have attached the code .....

code produce.txt

View 14 Replies View Related

C++ :: Using Template Function Inside Class In Separate Function?

Mar 26, 2014

i want to use a class to print data stored as vector or array with different data types. i also want the print function two take more than one vector or array or combination of both so that they can be written to file as two columns. so i wrote the following class:

right now it has only one member function for printing two vectors. later i'll add additional functions as required.

note: there has to be template functions inside the class
i also want the object to be global so that i need not pass it as an argument to other calling functions

class printdata
{
public:
template<typename T1,typename T2>
void SaveData( vector<T1> &data1,vector<T2> &data2, std::string var)
{

[Code]....

then i want to call this template function in another ordinary function written in a seperate cpp file

these function declarations are put in a header file. so i need know whether i should put the declaration of the template function in the header to use the function in different functions

View 4 Replies View Related

C/C++ :: Using Template Function Inside A Class In Separate Function?

Mar 26, 2014

i want to use a class to print data stored as vector or array with different data types.

i also want the print function two take more than one vector or array or combination of both so that they can be written to file as two columns.so i wrote the following class:

right now it has only one member function for printing two vectors. later i'll add additional functions as required.

note: there has to be template functions inside the class / i also want the object to be global so that i need not pass it as an argument to other calling functions

class printdata {
public:
template<typename T1,typename T2>
void SaveData( vector<T1> &data1,vector<T2> &data2, std::string var){
std::ofstream myfile;
std::string filename;

[code].....

then i want to call this template function in another ordinary function written in a seperate cpp file these function declarations are put in a header file. so i need know whether i should put the declaration of the template function in the header to use the function in different functions.

View 1 Replies View Related

C++ :: Template Function Don't Work As Inline Function?

Mar 8, 2014

I have this:

string input;
unsigned short choice;
...
istringstream valid(input);
...
if(!(valid >> choice))
{
//some error
}

Ok. My code is almost 1000 lines, and I have splited some functions in headers. But the same function doesn't work:

template <typename T> bool valid_input(const string& input, T var)
{
istringstream valid(input);
return (valid >> var);
}

You can check it here: [URL] The output is correct, but in my machine with C++11, MinGW 4.8 (64 bit in a 64bit-Windows8), the output is incorrect. Why?

If you want more specific info, the problem is that I use input, I think. I use std::getline(std::cin, some_string).

View 4 Replies View Related

C++ :: Convert Each Function To A Function Template

Dec 7, 2013

I am assigned this program by my instructor and he wants me to convert the function to function template. I do not know how to do that. How to get good grades in final.

#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
#include "Test.h"
struct char_list {
char head;

[Code] .....

View 1 Replies View Related

C++ :: Function In A Class Template

Mar 3, 2013

I have this class templates And This UML.I have to write this function +operator=(source: Array<ElemType, SIZE>): Array<ElemType, SIZE> but I do not know how to start the declaration / or start the function. I have to return a template but I do not know how to do it,

UML
Array<ElemType, SIZE>
-elements: ElemType[SIZE]
+Array()
+Array(source: Array<ElemType, SIZE>)
+operator=(source: Array<ElemType, SIZE>): Array<ElemType, SIZE>
+operator==(other: Array<ElemType, SIZE>): Boolean
+operator!=(other: Array<ElemType, SIZE>): Boolean
<<L-value>>+operator[](index: Integer): ElemType
<<R-value>>+operator[](index: Integer): ElemType

[code]....

View 4 Replies View Related

C++ :: Template Function Of A Class

Feb 3, 2013

I want to use a template function of a class.

This is my code:

#include "Comparison.h"
#include <iostream>
using namespace std;

int main(int argc, char** argv) {
Comparison c;

[Code] ....

But I get the error message:

main.cpp:10: undefined reference to `int Comparison::max<int>(int, int)'

View 2 Replies View Related

C++ :: Function With Template Arguments

May 26, 2013

I'm trying to create a callback wrapper for pointers to member functions of any class by using templates, std::function and std::bind. This will be used to send incoming sf::Event's to classes who register callbacks with an event manager. I based my code off of the example on this page: URL.....Here's what I have:

class EventCallback
{
std::function<bool(const sf::Event&)> func;

public:
template<typename T>
EventCallback(T* object, bool(T::*func)(const sf::Event&)) { func = std::bind(func, object, std::placeholders::_1); }
bool run(const sf::Event& evt) { return func(evt); }
};

[code]....

View 4 Replies View Related

C++ :: Template Function In Struct

Nov 6, 2014

I understand template functions and how to call them explicitly when no arguments are passed to them but can't seem to instantiate them explicitly when it resides within a class or struct.

struct Creator {
template <class T>
T * New(T * p) {
return new T;
}
};
Creator cr;
MyClass * pMy = cr.New<MyClass>(); //gives compile error

The compiler complains about MyClass (or any other) being used illegally in expression ...

View 6 Replies View Related

C++ :: Invoke A Template Function?

Sep 24, 2014

I wrote out this coding to deal with template functions, but how would I invoke the function and to display the statements which im trying to invoke?

#include <cstdlib>
#include <iostream>
using namespace std;
#include <string>

[Code].....

View 2 Replies View Related

C++ :: Passing Map Templates To Function Template

Feb 21, 2014

I was just wondering how is this generally resolved. Let say you have this large function that runs in two modes. In the first mode it evaluates the data passed to a function as a map the the second mode it fills the map. example:

Code:
template <typename Map, typename Int>
void func(Map & map, Int i){
int z = 0;
string zz;

[Code] ....

The point is i do not want to write a large function just to include different modes so i decided to set "i" to be a mode identifier. However when i want to compile my function given two modes i get an error since the modes are not recognized (obviously). if i pass map as

Code: map<int,int>
and mode 1 i get an error here :
Code: map[z] = z; besause map
Code: map[z] expects z to be an int not string and the other way around (though in practice this cannot happen since i set the modes). So am i restricted to writing my function for both modes separately (polimorf.) or there is a way to make my example work.

View 1 Replies View Related

C++ :: Template Function As Member Of Class

Apr 15, 2014

I want to have a template function that is a member of a class. Is this possible? This code snippet is how I would think the syntax would go, although it doesn't compile. How would I achieve the same effect?

Code:
class myclass {
public:
int member ;
} ;
template <typename T> void myclass::func( T& arg )

[Code] .....

View 4 Replies View Related

C++ :: Passing Pointer Into Template Function

Oct 14, 2014

I'm trying to pass the pointer of a dynamic array into a template function, but it keeps telling me there is no matching function to call because the parameters I'm passing in are wrong. how to make the function accept the pointer.

//main
int main()
{
srand(unsigned(time(NULL)));
int size;
int *list;
int *listCopy;

[code].....

View 4 Replies View Related

C++ :: Passing A Function As Template Parameter

Dec 26, 2013

Pseudocode:
template<typename T /*, some parameter for member_function */>
class Foo {
public:
void someFunction() {
T t;
t.member_fuction(...);
} }

I'm trying to make the call to T::member_function a templated value because member_function might vary by name in my scenario. Since std::mem_fn isn't a 'type', i can't do something like Foo<std::string, std::mem_fn(&std::string::clear)> foo;

I also want to take into account that member_function might have more than one parameter. That is, the first parameter will always be something known but there might be other defaulted parameters.

The only thing I can think of is to make a proxy structure, something like this:

template<typename T, T> struct proxy;
template<typename T, typename R, typename... Args, R (T::*member_function)(Args...)>
struct proxy<R (T::*)(Args...), member_function> {
R operator()(T &obj, Args.. args) {
return (obj.*member_function)(std::forward<Args>(args)...);
} }

Which would then allow me to do (for example) this:

Foo<std::string, proxy<void(std::string::*)(), &std::string::clear> >

when Foo is implemented like this:

template<typename T, typename member_function>
class Foo {
public:
void someFunction() {
T t;
member_function()(t);
} };

That implementation works for me.

View 10 Replies View Related

C++ :: Undefined Reference To Template Function

Oct 21, 2013

I am coding a RTS game but I cant compile my dataLoader function. It gives that errors when want to call it:

//Window size
int width;
int height;
if( !dataLoader<int>( width, "settings/resolution.txt", "width" ) || !dataLoader<int>( height, "settings/resolution.txt", "height" ) )

[Code] ....

View 7 Replies View Related

C++ :: Static Variable And Function With Template

Jul 18, 2012

I try to create small project in order to better understand how key word static works with templates . However some compiles errors crush my plan.

1>------ Build started: Project: 4.2b - Ex 1. Static Variable for Array Def Size. Templates, Configuration: Release Win32 ------
1> main.cpp
1>c:all myс++ha level 6solution level 6solution level 64.2b - ex1. static variable for array def size. templatesarray.cpp(40): error C2724: 'Array<Type>:efaultSize' : 'static' should not be used on member functions defined at file scope

[Code] .....

View 7 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved