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


ADVERTISEMENT

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 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++ :: 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 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++ :: Use Of Template Classes In Other Template Classes

Jan 24, 2012

I'm trying to make a template class which holds a template list I made. The list consists of template nodes (another template class I made).

My problem is that in some places (not everywhere) the compiler says that I'm trying to access private members of the node's class.

For example, if I define my node like this:
template<class T>
class CoefNode {
private:
T coef;

[Code]....

View 5 Replies View Related

C++ :: Declaration Of Template Specialized Classes

Aug 12, 2014

class intClass{};
class stringClass{};

template <typename T>
class Mediator {
// bunch of code
};

I want Mediator<int> to declare intClass friend, Mediator<std::string> to declare stringClass friend etc..., without having to redefine the entire specialization

template<>
Mediator<int>::friend intClass;

View 5 Replies View Related

C++ :: Template Classes And Inline Methods

Aug 17, 2012

I have a template class which defines a few heavy methods. For now, they are defined in the same .h file as the class definition, but i`d like to have them in a separate .cpp file.

A situation i find you describe in the FAQs arises: [URL] ....

Problem: the export keyword has been deprecated in c++0x, if i recall correctly, and has never been implemented in any of the compilers i am using (msvc, gcc).

#Including the the .cpp file after the class definition (as described in the second post of the FAQ) works.

another question: i have methods that dont use any template code. Can i somehow declare them as such? (more of an esthecial question, which would make it easier to distinguish between template and non.template code).

View 6 Replies View Related

C++ :: Way To Restrict A Template-capture To Certain Types / Classes

Nov 16, 2014

I was creating a template and I realized that certain data-types/structs/classes would not be applicable to my template.This would cause bugs and errors if used incorrectly. Is there a way to restrict a template-capture to certain types/classes?

View 2 Replies View Related

C++ :: Two Classes Derived From Same Template Class And Operator

Mar 11, 2013

class A {
// is abstract
};

class B : public A {
// ...
};

[Code] ....
[Code] ....

main3.cpp: In member function ‘FooB& FooB::operator=(const FooC&)’:
main3.cpp:46:44: error: expected ‘(’ before ‘other’
main3.cpp:46:49: error: no matching function for call to ‘Foo<C>::Foo(const FooC&)’
main3.cpp:46:49: note: candidates are:
main3.cpp:19:2: note: Foo<T>::Foo() [with T = C]
main3.cpp:19:2: note: candidate expects 0 arguments, 1 provided
main3.cpp:16:25: note: Foo<C>::Foo(const Foo<C>&)
main3.cpp:16:25: note: no known conversion for argument 1 from ‘const FooC’ to ‘const Foo<C>&’

Is there any way to make it work?

View 1 Replies View Related

C++ :: Passing Matrices Into Classes?

Sep 15, 2013

I am currently trying to pass a matrix (multidimensional array) from my main into a function in a class. As usual, you have to include all array sizes, except the first. Unfortunately, the size saved under a variable. When I write it in the square brackets, it doesn't work.

Example:

//main
int main () {
int n = 5;
random object;
object.declare_variable(n);
int array [3][n];
object.pass_matrix(array);

[code].....

I also tried, putting the variable 'var' in the public section above the void and declaring it as static, but still there are error messages; fewer, in my case:

...not an integer constant

So what should I do? Id like to repeat that the int n will vary, which is why I can't just directly write down the size.

View 9 Replies View Related

C++ :: Passing Classes As Parameters?

Oct 14, 2013

how would I pass this parameter and how/why is it not working this way? I've tried many different methods to this and I can't quite seem to figure it out.

studentList student;
student.push(252875, "Jerry", "UTPA");

What I thought would work

class student {
public:
int id; //student ID number
string name; //student’s name
string university; //student’ university
};
//student list is a doubly linked list of students.

[code]....

My header file.

I am honestly not sure where to start here. I would assume that it would know what to do with the varibles but it doesn't seem to want to accept them. It gives me

Error1error C2660: 'studentList::push' : function does not take 3 arguments

2IntelliSense: no suitable constructor exists to convert from "int" to "student"

View 11 Replies View Related

C++ :: Passing Classes By Reference?

Mar 1, 2013

I make a class (it stands for an ARMA time series), and I have a method wich modifies some of its variables. In other part of my program I have a function wich receives one object of this class as a parameter and, at some point, it calls the method of the ARMA class to modify it; here is my deal I want to pass the ARMA class by reference to this function, because I want the variables of the instance I'm passing to be modified, not those of a copy the method uses. Also, I would like not to declare the function inside the class ARMA, cause I use it in other places too (it's basically a Nelder-Mead optimization what it performs).

Here is a code wich sketches what I've been trying, and exactly the error message I get is "modifyParameter has not been declared".

#include <iostream>
#include <cstdlib>
using namespace std;
class ARMA{

[code]....

View 5 Replies View Related

C++ :: Creating Template Of Array To Use For Classes Line And Point

Jun 14, 2012

I want to create template of of Array in order to have possibility use this template for classes Line and Point.

Code:
// Array.h
// Templated Array class containging Ts
#ifndef Array_H
#define Array_H
template <class T=double> class Array {

[Code] .....

View 10 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++ :: 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++ :: Can A Friend Function Work For Two Classes?

Mar 23, 2013

If yes then how?

View 6 Replies View Related

C/C++ :: Classes - Find Factorial Of Any Given Function

Aug 2, 2014

I wrote this code to find the factorial of any given function ., works fine but when i put it in a class... it gives me an error ::assignment of read only variable fact;

#include <iostream>
using namespace std;
const static int fact=1;
class My_Factorial {
public:
int x;
void Get_Number(){
cout<<"enter a number to find its factorial";

[Code] ....

View 3 Replies View Related







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