C++ :: Variadic Templates And Type Composition?

Jan 28, 2014

Let's say I have a variadic type A and a non-variadic type B:

Code:
template <typename ... Args>
class A
{};
template <typename T>
class B
{};

Now, I'd like to do the following (pseudocode since I don't know how to do this yet):

Code:
template <typename ... Args>
class C: public A<B<Args1>,B<Args2>,B<Args3>....>
{};

Essentially, I'd like to take the parameter pack used for C and compose B around each element individually, then pass the result to A.

how I can do this?

View 2 Replies


ADVERTISEMENT

C++ :: Templates (composition) Exception Handling Run-time Error

Aug 4, 2012

The code is compiled.

If I do loops for push and pop fucntions in main.cpp the same size as Stoke everything is working properly

If loops are larger than the Stack size that goes here is a picture in the console (see screen print)

Code:
//
//(---.Array_hpp---)
//
#ifndef Array_HPP// Preprocessor gates
#define Array_HPP
#include <sstream>
#include <iostream>
#include <exception>
template <class Type>//Remove the "=double" default parameter.

[code]....

View 4 Replies View Related

C++ :: Variadic Templates And Overload Resolution

Jan 2, 2014

I'm trying to learn how to use variadic templates, and I decided a great example would be serializing a series of types into a stringstream:

Code:
// Send a fully constructed message.
virtual void send(ostringstream &msg) = 0;
// Construct a message from the arguments and send it.
// This is the usual entry point.
template <typename ...Args>
void send(Args ...args {

[Code] ....

This works fine, so far as I can tell. However, I decided to see if I could specialize the way certain types are serialized. I tried using a Google Protocol Buffer object as an example, and added this:

Code:
// Handle a protocol buffer type while constructing a message.
template <typename ...Args>
void send(ostringstream &msg,
const google::protobuf::MessageLite &protobuf, Args ...args) {
std::string msg_str = protobuf.SerializeAsString();
msg << msg_str;
send(msg,args...);
}

I would expect this overload to be preferred over the generic T overload when a protobuf object (which always inherits from MessageLite) is passed into send() anywhere in the list. However, this is not happening. I am getting an error message to the effect that << doesn't know how to deal with my concrete type, pointing at the T overload.

View 4 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++ :: Can Use Templates To Make A Multi-type Linked List?

Apr 28, 2014

If I wanted an int connected to a float connected to a string connected to a POD, would all I have to do is :

Code:

template<class T, class X>
struct node {
T data;
node<X> *next;
};

Or would I be forced into using polymorphism?

View 10 Replies View Related

C++ :: Composition - Can't Use Set Function Of Parent Class

Apr 5, 2013

From parent class, I mean the class whose obj has been made in the class after that.

#include <iostream>
using namespace std;
class a{
int x,y;
public:
a(int u = 0, int v = 0);
void setXY(int,int);

[code].....

View 1 Replies View Related

C++ :: Composition - Writing Programs In Multiple Files

Oct 23, 2012

So lately I've been writing multiple header and cpp files and I would always the same error when I finally #include headers in my main.cpp. This error

Code:
undefined reference to `...`

On Youtube videos I see people doing this and their work magically compiles correctly. I found out that when I #include the headers' cpp files instead, my programs would compile. I use Code::Blocks with GNU GCC compiler.

View 2 Replies View Related

C++ :: Composition And Member Access Inside Composed Structure

Jan 18, 2013

I have a question regarding composition and accessing members "deep" inside the composed structure. For example;

class A {
private:
int m_myInt;
public:
int myInt() const {return this->m_myInt;};
void myInt(int newInt) {this->m_myInt = newInt;};

[Code] ....

Now, from somwhere I have access to an object of type B where I want to update the A::m_myInt. How would you do this without "breaking" the whole purpose of private/public members?

B myB;
myB.m_a.myInt(3); // Not allowed, and not desireable

I thought about implementing access through functons kind of like;

A & B::a() {return this->m_a;};
myB.a().myInt(3);

but I'm worried that this exposes my B::m_a-object too much. This would allow

myB.a() = A();
, right?

The following is a more desireable way of acces, but doesn't work for updating;

A const & B::a() {return this->m_a;};
myB.a().myInt(3); //Disallowed? myInt(int) is non-const.

What about this? Is this a good way of doing it?

class A {
private:
int m_myInt;
public:
int myInt() const {return this->m_myInt;};

[Code] ....

I guess it works? It would lead to a lot of data shuffling in case of larger sub-components.I would really like to do the following without exposing my components so much:

B myB;
myB.a().myInt(3);

Can it be done?

View 11 Replies View Related

C++ :: Develop Month Calendar By Designing A Class - Inheritance And Composition

Nov 10, 2014

In this assignment the student should develop a month calendar by designing a class called calendarType . This class uses two other classes (dateType and dayType) as described below:

1. dayType Class: This class has been designed by students in Lab1 exercises. Referee to it.
2. dateType Class: This class is designed and implemented to keep track of data. This class has been provided it to you. Study it first then add definitions and implementations of the following operations to this class:

- Test whether the year is a leap year. Leap year is identified by 3 criteria :
- The year is evenly divisible by 4;
- If the year can be evenly divided by 100, it is NOT a leap year, unless;
- The year is also evenly divisible by 400. Then it is a leap year.
- Return the number of days in the month. For example, if the date is 12/3/2014, the number of days to be returned is 31 because there are 31 days in March.
- Return the number of days passed in the year. For example, if the date is 18/3/2014 the number of days passed is 77. Note that the number of days returned also includes the current day.
- Return the number of days remaining in the year. For example, if the date is
18/3/2014 , the number of days remaining in the year is 288.
- Calculate the new date by adding a fixed number of days to the date. For example, if the date is 18/3/2014 and the days to be added are 25, the new date is 12/4/2014.

To print monthly calendar using calendarType class, you must know the first day of the month and the number of the days in that month. Thus, you must store the first day of the month, which is in the form of dayType and the month and the year of the calendar. Clearly, the month and the year can be stored as an object of the form dateType by setting the day component of the date to 1, and the month and year as specified by user.

Design the class calendarType so that the program print a calendar for any month starting 1/1/ 1500 which is Monday. To calculate the first day of a month, you can add the 2 appropriate days to Monday of January 1, 1500. For this class identify and implement the following operations:

- Determine the first day of the month for which the calendar will be printed. Call this operation firstDayOfMonth.
- set/get month.
- set/get year.
- Print calendar for particular month.
- Add the appropriate constructors to initialize the member variables.
- Write a test program to print the calendar for either a particular year or a particular month.

View 1 Replies View Related

C :: Variadic Macro Function

Sep 12, 2013

I'm doing right now is creating a function that callocs (I prefer this to malloc) and returns a string, and it will work similar to printf, I'm calling the function alloCpy(),I have several values that I need in a malloced string, so I call Code: myAllocedString = alloCpy("Value 1 is %s, value 2 is %s, and value 3 is %d", str1, str2, num); To do this I'm using the Variadic Macro, the reason I'm not just using a Variadic Function such as this: Code: char* alloCpy(char *format, ...) {} is because I need to append NULL to the end for the sake of looping through arguments, and I'm understanding it thusfar, but I have a few issues, first of all, I tried defining the Macro in a header file, but when I try to call it I get the error "Undefined reference to alloCpy". Also, to loop through arguments to get string lengths I'm using va_arg(args, char*) which requires all the arguments to be of type char*. Here is my code:
myheader.h:

Code:

#define alloCpy(format, ...) _alloCpy(format, ##__VA_ARGS__, NULL);
char* _alloCpy(char *format, ...); mycfile.c: Code: char* _alloCpy(char *format, ...) {
va_list args;
va_start(args, format);
int args_len = 0;
}

[code]....

So, how can I do this to, first of all, make my macro function accessible from other files importing myheader.h, and second, how can I make it accept any type of argument like printf, so that my example above would work?

View 3 Replies View Related

C++ :: Inheriting One Variadic Class From Another?

Jan 30, 2014

I have a variadic base class with a pure-virtual function per type:

Code:
template <typename ... Types>
class Base;
template <typename T, typename ... Types>
class Base<T,Types...>: public Base<Types...>
{
public:
using Base<Types...>::doSomething;

[Code] ......

Now, I'd like to inherit from it using another variadic class, which provides implementations of doSomething(), but I run into trouble --- where do I indicate it derives from Base?

Code:
template <typename ... Types>
class Derived;
template <typename T, typename ... Types>
class Derived<T,Types...>: public Derived<Types...>

[code]....

I see two possible approaches:

First, virtual inheritance *might* get me what I want, but I don't know how bad a performance hit that might be.

Second, I could do some magic where the full set of types is captured in a tuple at the lowest level and continually passed up, then re-expanded in the base case to indicate Base inheritance. However, I'm not sure if that can be done in an unambigious manner; I can't have two variadic packs at once (Types... and the tuple contents), and I'm not sure if there's a way to use enable_if to check if an arbitrary template type is any kind of tuple.

View 2 Replies View Related

C++ :: Variadic Template Basic Syntax

Jul 31, 2014

I had to learn how to use variadic templates recently, and had trouble finding simple examples that just showed the basic syntax.

So I decided to write one myself. Admittedly, it's a bit on the long side, but that is mostly because it includes five specializations.

insert Code:
// Variadic.C
// Compile command: g++ Variadic.C -std=c++0x
// I used GCC version 4.6.3 on Ubuntu.

// This file contains a basic variadic template with five specializations.
// It is intended for non-software engineers who are looking for a simple
// example of variadic template syntax.

[Code] ....

View 3 Replies View Related

C++ :: How To Remove Last Argument In Variadic Template

Nov 1, 2013

I wonder if it is possible to remove the last argument in an argument pack? Below is an example on what I want to accomplish:

template<template<int...> class A,int... Ints>
A<remove_last_int<Ints...>::list> func(const A<Ints...> & a0)
{
A<remove_last_int<Ints...>::list> a;
...
//Here a set the members of a based on a0.
...
return a;
}

For example, I want the return a A<1,2> value from (const A<1,2,3> & a0)

View 8 Replies View Related

C++ :: Enable If With Variadic Template Arguments

Sep 17, 2014

template <typename FIRST, typename... REST, typename std::enable_if<std::is_convertible<FIRST, Base*>::value>::type* = nullptr>
void foo (FIRST first, REST... rest) {}

that successfully allows me to enable the function foo() only if FIRST is convertible to Base*, but I also only want foo() enabled if each type in REST... meets the same condition. What is the syntax for that? If no such syntax exists, how to achieve that effect?

View 7 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++ :: Variadic Function - Parameters Get Passed In Reverse

Nov 17, 2014

I noticed that when using variadic functions, if I pass the va_arg() as parameter to a function, the parameters get passed in reverse. Is that expected?

For example, the following code outputs
Code:
1 2
2 1

Code:
#include <iostream>
#include <stdarg.h>

void foo_func(int v1, int v2)
{
std::cout << v1 << " " << v2 << std::endl;

[Code] .....

View 3 Replies View Related

C++ :: Expanding Variadic Template Arguments In Lambda

Feb 1, 2013

I'm trying to expand a template + argument parameter list inside a lambda function like this:

template <typename Class, typename ...Args>
static void create(Args ...args) {
// Perform pre-thread creation work.
std::thread([=]()

[Code] ....

But this does not work:

The compiler error is "error: parameter packs not expanded with ‘...’:|"

However, when I do the following:

template <typename Class, typename ...Args>
static void create(Args ...args) {
// Pre-thread work.
auto tthr = [](Args ...ar) -> void {

[Code] ....

It works just fine. That shows that lambda threads are able to take variadic arguments...

So here is my question; what is the correct capture clause for capturing the variadic object correctly?

View 3 Replies View Related

C++ :: Ambiguous Call On Overloaded Variadic Template Operators

Oct 30, 2013

When compiling the code

#include "tensor.h"
int main() {
Tensor<2,-2> m = {{1,2},{1,3}};
Tensor<2> v = {1,5};
std::cout<<m*v<<"

[Code] ....

Why do I get an ambiguity and why is not the wanted operator*-overload (the last one in the tensor.h file) not even mentioned as one of the candidates? Is it clear what I want to do? And if so, what can I do to make the call unambiguous?

View 3 Replies View Related

C++ :: Variadic Template Function Parameters And Method Pointers?

Oct 24, 2013

I have been experimenting with variadic templates with the aim of caching a call to a class method by storing away the object pointer, method pointer and parameters. I've actually had some reasonable success but have now hit a stumbling block. I now wish to wrap my parameters in a simple template class when I cache them. My success is as follows:

Using variadic template functions to store these pointers and paremeters;

I'm able to pass a method pointer and unwrapped parametersI'm able to pass wrapped parameters on their own.I'm NOT able to pass a method pointer and wrapped parameters I set up a little prototype project to demonstrate the issue and added comments above the function calls to indicate the compilation results. Here is the code:

Code:
#include "stdafx.h"
//////////////////////////////////////////////////
// Basic class with a simple method
//////////////////////////////////////////////////
class MyClass {
public:
char Method( int i, float f ) {
return 'A';

[code]....

But I'm convinced it should take three arguments, the method pointer and two wrapped parameters. Visual studio even suggested it should as shown below:

View 3 Replies View Related

C++ :: Templates Without Arguments

Jan 22, 2013

Some reading through C++ code I come across template deceleration without any type , I have tested the code it compiles too

Code:
template<>
class abc {
}
similarly template usage

Code:
abc<> a;

example of such usage can be found here [URL] ....

View 5 Replies View Related

C++ :: Linked List Using Templates

May 27, 2014

I decided to make a linked list program using classes and templates.I implemented my linked list and added some basic functions, everything worked just fine. Then I proceeded to add templates...First, the error list:

#pragma once
template<class T>
class Node {
private:
Node* next;

[code]....

To sum up: Something's wrong with the templates that I used in "List.cpp" and what it could be.

View 5 Replies View Related

C++ :: How To Allocate Memory When It Comes To Using Templates

Oct 25, 2013

I'm currently learning templates -- & my logic is in a knot with what I am trying to do which is the following:

-Create a function name load
-Accepts a filename (the filename is a text file of integers)
-Open the file
-Create an array(dynamically allocating an array) filling it with the elements read in from the file & returns the array(so that the return type of the array is a pointer to the element type of the array).

//Header file:
#ifndef BUBBLE_SORT_H
#define BUBBLE_SORT_H
#include <iostream>
template <typename T>
void load(std::string filename, T *&arr, int *size);

[code].....

how to allocate memory when it comes to using templates..

View 2 Replies View Related

C++ :: Reading Values From Templates

Mar 14, 2013

After asking the user to input 2 values i expect my program to read them and then output whether they are equal, bigger or smaller than one another. However i am getting no output what so ever when i input the values

code below:

#include <iostream>
#include <cmath>
#include <cstring>
#include <string>
#include <string.h>

using namespace std;

int intInput1, intInput2;
float floatInput1, floatInput2;
int x, n;

[Code] .....

View 1 Replies View Related

C++ :: Templates And Memory Occupancy

Dec 15, 2013

Let us consider the following two classes:

class case1
{
public:
int n;
float x;

[code]....

Now, let's suppose that I instantiate an array of 100 elements of each class:

case1 c1[100];
case2<20> c2[100];

My question is this: will c2 occupy roughly half of the memory than c1?will the value c1.n be allocated 100 times, while the value c1.n wil be allocated only once?

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++ :: How Templates Are Implemented Internally

Feb 25, 2013

How templates are implemented internally?

Theoretically templates are nothing but a generic routines. But how it has been implemented internally?What complier exactly does?

View 3 Replies View Related







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