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


ADVERTISEMENT

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++ :: 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++ :: 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 By Reference With Templates

Aug 26, 2014

Why wouldn't this code compile when adding '<double>' after the function call?

template<class T>
T add(T& a, T& b){
return a + b;
}
int main() {
int a, b;
cin >> a >> b;
cout << add<double>(a,b);
}

Compiler error:
cannot convert 'a' (type 'int') to type 'double&'

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 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++ :: Bubble Sorting With Function Templates

Jun 21, 2013

i'm new to C++ i came across this bubblesort program earlier relating to class templates i was wondering how to make this into simple function templates

#include<iostream>
#include<iomanip.h>
#include<conio.h>
#include<stdio.h>
using namespace std;
template <class t>
class bubble

[Code] ....

View 3 Replies View Related

C/C++ :: Error In Member Function Using Templates

Mar 5, 2014

template <class T>
void Arreglo<T> :: Registro (ifstream& Entrada) {
Entrada >> Cantidad;
Dealer = new T [Cantidad];
for (int i = 0; i < Cantidad; i++) {

[Code] .....

It says the following error when I comile it:

error: expected type-specifier before 'Detail'
(*(Dealer + i)).Modelo = new Detail[(*(Dealer + i)).AmountModels];
error: expected ';' before 'Detail'

View 3 Replies View Related

C/C++ :: Explicit Initialization Of Function Templates

Feb 28, 2013

Why will i use explicit instantiation of a template, for a type? If I do not use explicit instantiation, the template is used to create the necessary function then what is the use of explicit instantiation?

template <class Any>
void Swap (Any &, Any &);
// template prototype  
template <> void Swap<job>(job &, job &);
// explicit specialization for job

[Code] ....

In the above eg. explicit instantiation is done for char type. What is the use of this?? If the compiler can make use of the template to make a fn for char type.

<eg. taken from C++ Primer>

View 4 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++ :: Variadic Templates - Enter Unlimited Amount Of Types In Function

Feb 25, 2013

I'm looking for a way to enter an unlimited amount of types in the <> part of a template function, I found Variadic templates but I'm not sure if it can do it, all the examples I've found are similar to the C argument list and don't use the <> part of the template at all.

I tried this, but the overload is ambiguous?

#include <iostream>
#include <typeinfo>
template<typename T>
void stuff() {
std::cout << typeid(T).name() << "

[Code] ....

View 2 Replies View Related

C++ ::  Errors With Using Templates - Unable To Match Function Definition To Existing Declaration

Apr 13, 2013

I've written the following code and keep getting the errors:

Error1error C2244: 'Supermarket<temp>::operator =' : unable to match function definition to an existing declaration
Error2error C2244: 'Supermarket<temp>::setName' : unable to match function definition to an existing declaration
Error3error C2244: 'Supermarket<temp>::setArea' : unable to match function definition to an existing declaration

#ifndef SUPERMARKET_H
#define SUPERMARKET_H

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

[Code] .....

I moved the files to the .h file, and now I'm getting

Error2error LNK1120: 1 unresolved externals

View 11 Replies View Related

C++ :: Passing Class As Type In Template Class

Nov 30, 2013

I am trying to pass a class as a type to a template class. This class's constructor needs an argument but I cannot find the correct syntax. Is it possible?

Here is an example of what I described above. I did not compiled it, it is for illustrative purpose only. And of course argument val of the myData constructor would be doing something more useful than simply initializing an int....

template <class T>
class templateClass {
templateClass() {};

[Code]....

My real code would only compile is I add the myData constructor:

myData () {};

and gdb confirmed that it is this constructor that get called, even with dummy(4).

View 4 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++ :: Passing 2 Dimensional Array Through Median Function To One Of 2 Other Function

Aug 20, 2013

I want to use one median function "selectfunction" to choose one of the 2 other functions at random to pass my 2-dim array to the selected function. There is a problem in the median function

#include <iostream>
#define random(x)(rand()%x) // for random number between numbers of 0 and 1
using namespace std;
void proc1 (int iArray[][2]);
void proc2 (int iArray[][2]);
void selectfunction(int iArray[][2]);
int A[4][2] = {{1, 2} , {3, 4} , { 5, 7} , {8, 1} };

[Code]...

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







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