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


ADVERTISEMENT

C++ :: Passing A Function Pointer As Template Argument To A Class

Aug 15, 2012

I have in the past written code for templated functions where one function argument can be either a function pointer or a Functor. Works pretty straightforward.

Now I am in a situation where I am actually trying to pass a function pointer as template argument to a class. Unfortunately this does not work, I can pass the Functor class but not the function pointer. Below code illustrates the issue:

Code:
#include <string>
#include <iostream>
#include <sstream>
#include <cstdlib>
// For demonstration
const char * external_library_call() {
return "FFFF";

[Code] .....

The idea is to have the definition of the Record class simple and readable and have a maintainable way to add auto-conversion functions to the class. So the lines I commented out are the desirable way how I want my code to look. Unfortunately I could not come up with any way that was close to readable for solving this.

View 3 Replies View Related

C++ :: Template Function Parameter Passing By Reference Instead Of Copy / Pointer

Sep 19, 2014

Basically I'm trying to pass an object as a reference to the template function, rather than a copy as it's seeing. I'm needing to do this without editing Obj::Call to accommodate a reference as its first parameter, as it'd break other calls.

You'll notice in the following code the object will be destroyed upon passing, while the object defined is still in-scope due to the infinite end loop.

#include <iostream>
#include <string>
using namespace std;
class Obj {
public:
string name;
Obj(string name): name(name) {cout << "create " << this << endl;}

[code]....

In the past I tried ref(), which appeared to stop this happening, however it created a blank copy of the object instead.

View 3 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++ :: 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++ :: Passing Variadic References To Template Function?

Dec 14, 2014

I'm having some problems in understanding how the code below works and why it produces the output it produces.. What I'd expect is that both functions, namely `add_1' and `add_2', would print the same output; but I've been proven wrong :/ So why does the second one get different memory addresses for the same variable?

Code should be self-explaining:

Code: template<typename... Types>
void add_1(Types&&... values)
{
// by the way: why do i have to use `const int' instead of `int'?
std::vector<std::reference_wrapper<const int>> vector{
std::forward<Types>(values)...};
std::cout << "add_1:" << std::endl;
for (const auto& value:vector) {
std::cout << &value.get() << std::endl;

[code].....

View 4 Replies View Related

C++ :: How To Prevent Someone Passing Classes To Function Template

Sep 13, 2013

Let say i have a following scenario:

a function like this.

Code:
template <typename T1>
print (T1 x){
cout << x << "
";
}

How do I prevent user passing a class or a structure or aanoter function to my function print. I mean i know if a wrong thing is passed that i'll get an error eventually but is there a way to explicitly check what has been passed. How is this done usually ?

View 6 Replies View Related

C++ :: How To Pass Function Pointer As A Template Parameter

Jun 13, 2013

void extf(int a) { }
template<typename P>
struct A {
// 1
template< void (*F)(P) >
static void call(P arg) {

[Code]...

Why it is not working? What would be a proper way to pass function pointer as a template parameter?

View 6 Replies View Related

C :: Passing Structure Pointer To A Function

Aug 24, 2014

I am trying to wright a program that takes student grade data from a command line file, calculates a final grade, and copies the final grades to an output file. So far I have two functions, one that creates a student structure by allocating memory for it and returning its address, and one that should take that address and fill it with data from a line from the input file. My ultimate goal is to use a linked list to connect all the structs, but for now I just want to get the functions working. When I run what I have so far, I get an error C2440 (using visual 2010) that says "cannot convert from 'cStudent *', to 'cStudent', and points to the line where I call my fill function. How should structure pointers be passed?

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student // Declaring student structure globally.

[Code] .....

Also, here is a sample of what a line from the input file would look like:
Bill Gates, 60, 54, 38, 62, 65, 60, 50

View 2 Replies View Related

C :: Passing Array Of Pointer To A Function

Sep 7, 2013

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CMD_LINE 500
void tokenize(char *cmd_ln, char *fun_tknzd[], int *argument_cnt);

[Code] ....

I am trying to pass the value of fun_tknzd to str_tknzd

View 4 Replies View Related

C++ :: Passing Array As Pointer To A Function?

Apr 24, 2014

I can clearly understand how to pass a dynamic array to a function and modified within the function..

My aim is to get back the array initialized as I am trying on the next sample of code..

Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <fstream>
using namespace std;
#define N3//number of bodies
void initialise( double *M[], double *X[], double *y[])

[code]....

View 14 Replies View Related

C++ :: Passing Object By Pointer To Function?

May 20, 2014

I have a Qt classes as follow:

Code:

class Vehicle {
public:
void AddData(QString str, Data* data) {
_myDataMap.insert(str,data);
} virtual void Init();

[code].....

My questions are:

After the main function called d1->Modify; the data stored in _myDataMap will get modified too.

What is the more appropriate way of passing the Data through AddData in such case?

If i do AddData(const Data & data), i will not be able to use inheritance of Data, i.e passing a subclass of Data to AddData.

View 3 Replies View Related

C++ :: Labels As Pointer - Passing Address To A Function

Mar 7, 2014

Is there such thing as passing a winforms label by reference? For example, can I create a pointer label and pass the address to a function? I've looked online but couldn't find anything. Perhaps that's a sign?

View 1 Replies View Related

C++ :: Passing Pointer To A Function - Calling Routine

Dec 4, 2013

I have this code:

#include "stdafx.h"
#include <iostream>
using namespace std;
void square_cube(float *x,float *y) {

[Code] .....

The function should pass the square of the first input parameter and the cube of the second input parameter back to the calling routine. I thought I could use a recursion but its not going to work.

View 8 Replies View Related

C :: File Opened In Main And Passing Pointer To A Function

Sep 14, 2013

I am getting a few compile errors for what might be a simple thing to do. I am opening a file in main, passing that pointer to a function and checking the contents of that file with a regex before I pass it on to build a BST. I am getting the following compile errors, what is wrong. Here are the errors:

Code:
gcc main.c fileCheck.c -o tree
main.c: In function `fileCheck':
main.c:19: error: syntax error before "FILE"
fileCheck.c: In function `fileCheck':

[Code] .....

Fatal error: Command failed for target `tree' Here is the two files and header that seem to be causing me the problems.

main.c

Code:
#include "main.h"
//#include "node.h"
int main(int argc, char *argv[])
FILE *fp;
if (argc > 2)

[Code] ....

And the header file.
main.h

Code:
#ifndef MAIN_H
#define MAIN_H
#ifdef __cplusplus
extern "C" {
#endif

[Code] .....

View 2 Replies View Related

C++ :: Passing A File Pointer To A Function Is Producing Undesired Output

Oct 27, 2013

I am working on a project and decided to try something simple before I start adding items. I am calling a function from main and that function has a file pointer.

Here is my main.cpp

Code: #include <cstdio>
#include <string>
#include <iostream>
#include "main.h"
extern FILE *fp;
using namespace std;
int main(int argc, char *argv[])

[code]....

Here is the function:

Code:
#include <string>
#include <cstdio>
#include <iostream>
#include "main.h"

[Code] ....

My test file consists of several characters and digits. Nothing special and I at this point in time do not have any type of formatting that needs to be adhered to. I am simply wanting to read the file character by character and print it out. When I run the program, I get this symbol:

Code: If I use a printf statement, such as:
Code: printf("%s
", nextChar);

I get a segmentation fault.

My main.h Code:

#ifndef MAIN_H
#define MAIN_H
void scanner(FILE *);
//char getChar(FILE *);
#endif and lastly my scanner.h Code: #ifndef SCANNER_H
#define SCANNER_H
FILE *fp;
#endif

View 6 Replies View Related

C :: Passing Argument Of Incompatible Pointer Type - Warning In Function Call In Main

Jun 4, 2013

Code:
#include <stdio.h>
#include <stdlib.h>
int size_b_row1;
int size_b_col1;

[Code].....

View 2 Replies View Related

C++ :: Passing Same Template Value To Two Different Template Functions

Dec 11, 2014

I have been trying to get a hang on templates. I have the two following functions that that could be consolidated in a single template function:

void Attractor::updateFamilies(FamiliesController *_tmp, int _counter){

center.x = ofGetWidth()/2;
center.y = ofGetHeight()/3;
attractorCounter = _counter;
if(attractorCounter == 1){

[Code] .....

NotesController and FamiliesController have the same parent. The thing that I'm trying to grasp with templates is that is could something like:

template<class TYPE>
void Attractor::updateData(TYPE* *_tmp, int _counter){
center.x = ofGetWidth()/2;
center.y = ofGetHeight()/3;
attractorCounter = _counter;

[Code] ....

And then have another template function declaration for all the attractor functions where I pass the same template value as in the first one.

As you can see, I'm calling another functions inside called attractors(_tmp). I know that one way around it could be to get rid of that function and just do all the logic inside of each if statement. Is there any way to pass the same template function parameter within a template function parameter?

View 2 Replies View Related

C++ :: Passing Arguments From Incompatible Pointer Type - Warning In Function Call Transpose In Main Routine

Jun 4, 2013

#include <stdio.h>
#include <stdlib.h>
int size_b_row1;
int size_b_col1;
int main(void) {
double C[4][4] = {{1,3,5,2},{7,6,2,2},{1,2,7,3},{2,3,5,3}};
double TC[4][4];
transpose(C, TC);

[Code] ......

View 2 Replies View Related

C++ :: Passing Lambdas As Template Parameter

Oct 6, 2013

I've been playing around with this piece of code:

#include <iostream>
#include <string>
#include <algorithm>
template <void(*funky)(const std::string&)>
void callback()
{funky("Hello World!");}

[Code] ....

But when I try to build it, I get this error on line 24:could not convert template argument 'lambda' to 'void (*)(const string&) {aka void (*)(const std::basic_string<char>&)}'|

I thought the lambda expression I wrote would decay to a function pointer matching the template parameter. I can guess that the constexpr qualifier might have changed the type, but without it my compiler complains that lambda needs to be declared as constexpr...

So is there a way to pass lambda expressions as template parameters?

Without having to use std::function

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++ :: Passing Lambda As Template Parameter Not Working Correctly

May 30, 2013

I've was trying out a function template to automatically get the type of a lambda, but it seems that it won't compile

I've tried two different ways:

1.
template<class HASHER>
auto make_unordered_map(size_t bucketCount, HASHER const && hf)
-> unordered_map<string const, HASHER>&& {
return unordered_map<string const, int, HASHER>(bucketCount, hf);
} auto x = make_unordered_map(1, [](string const& key)->size_t { return key[0]; });

2.
template<class HASHER>
auto make_unordered_map(size_t bucketCount, HASHER const && hf2)
-> unordered_map<string const, int, decltype(hf2)> {
return unordered_map<string const, int, decltype(hf2)>(bucketCount, hf2);
} auto x = make_unordered_map(1, [](string const& key)->size_t { return key[0]; });

The test code are located here:

1. [URL] ....
2. [URL] ....

They are both based on the code that is stated to work in those examples. I.e.:

auto hf = [](string const& key)->size_t { return key[0]; };
unordered_map<string const, int, decltype(hf)> m (1, hf);

View 13 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

C/C++ :: Passing A Global Pointer?

Feb 29, 2012

Let's say I've got something like this:

struct Box{
//something
};
typedef struct Box* pBox;

[Code]....

function fun recieves the address(which is NULL) and then allocates the memory for the Box; Let's say I cannot return the address of new allocated p and I can't also use that pointer p(from main) without passing it into a function.

Q: How can I make it that I could operate in function "fun" as I operate on orginal pointer p(from main), right now I'm just passing the address to my function but I can't change the 'global' pointer p ;(.

I remember in pascal it's like:
"function(var pointer:[pointer to sth])"
and all is done.

View 14 Replies View Related

C :: Calling Function Via Function Pointer Inside Structure Pointer

Mar 14, 2013

I'm trying to call a function via a function pointer, and this function pointer is inside a structure. The structure is being referenced via a structure pointer.

Code:

position = hash->(*funcHash)(idNmbr);

The function will return an int, which is what position is a type of. When I compile this code,

I get the error: error: expected identifier before ( token.

Is my syntax wrong? I'm not sure what would be throwing this error.

View 3 Replies View Related

C :: Passing A Pointer To Array Of Structs

Nov 20, 2013

what I am trying to do is to pass to a function the address of an array of structs, so I can later modify the items within the struct, within the array

Code:
typedef struct { //A struct of name auctionint bidder;float bid;} auction;
void myFunction (auction * auctionItem[]){(*aucItem[x]).bid = y;(*aucItem[x]).bidder = z;}
int main(){auction theItems[10];
myFunction(theItems);} Where x, y, and z can be any number.

When I try to run my code the IDE (I'm using Code::Blocks 12.11) does not give me any errors, but it does give me a warning:

warning: passing argument 3 of '<function name>' from incompatible pointer type [enabled by default]

and the note:

note: expected 'struct <struct name> **' but argument is of type 'struct <struct name> *'.Also, when I run the program, it will crash and return garbage.

View 6 Replies View Related







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