C++ :: Template Parameter Automatically With Class Name

Mar 8, 2013

I have a triple hierarchy class:

template<class T> class Singleton;
class Base;
class Sub : public Base, public Singleton<Sub>;

I' using underlying auto pointers, that's why Singleton is a template class and Sub passes itself as a template parameter. I'm developing Singleton and Base and a public API allows anyone to add their own sub classes. I actually want a real triple hierarchy like this:

template<class T> class Singleton;
class Base : public Singleton<Base>;
class Sub : public Base;

So that external developers don't have to worry about templates and complexity. The problem with this is that my implementation in Singleton will now call the constructor of Base whenever I create an instance of Sub (since the template parameter is Base).I was wondering if this could be done by pre-processor macros:

template<class T> class Singleton;
class Base : public Singleton<__CLASS_NAME__>;
class Sub : public Base;

Where __CLASS_NAME__ is the class name that will be replaced by the pre-processor. Theoretically this should be possible, since the __PRETTY_ FUNCTION__ macro actually returns the class name. The problem is that one cannot do string-manipulation to remove the function name from __PRETTY_FUNCTION__.

how I can accomplish this so that the Sub class is not aware of inheriting from a Singleton<template> class?

View 9 Replies


ADVERTISEMENT

C++ :: Template With A Specialized Template Class Parameter?

Nov 2, 2014

how I want the code to look. Only problem is it doesn't work (Line 11). I have some experience with templates but I'm not a pro.

Basically I want the "Channels<3>" to be a type that I can use to specify a Cable with similar to vector<float/int> it would be Cable<Channels<2 or 3>>.

What have I messed up with the syntax?

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

[Code].....

View 4 Replies View Related

C++ :: Float As Template Parameter

Jan 16, 2014

Unless I'm missing something, it's now possible(ish)? A little concept is below, very rough around the edges. Still though, if this is valid by standard C++, why can't we have built-in support for float / double template parameters?

#include <iostream>
#include <tuple>
template<int Numerator, int Denominator>
struct Float {
constexpr static float value()

[Code] ....

View 7 Replies View Related

C++ :: Automatically Attaching Objects To Parent Class

Jul 8, 2013

In my program, I create controls by deriving base objects of them I've made. These controls are then are attached within the OnCreate() function via a method I've created. For example:

Code:
class tChat: public TextBox {
public:
void OnKeyDown(UINT &KeyCode) {
if (KeyCode == VK_RETURN) {
MessageBox(NULL, "Pressed enter!", NULL, 0);
[Code] ....

The use of AddControl() feels quite redundant and is only their to parse a pointer to txtChat's Parent. I'm trying to see if it's possible to remove this line and automatically associate txtChat to fMain.

Currently my hierarchy looks like:

[User's derived Form] -> [MDIForm or Form] -> [FormBase] -> [Object]
[User's derived Control] -> [TextBox, etc..] -> [Control] -> [Object]

The user can then derive the Form and Controls and use their virtual OnEVENT functions to handle all the messages they expose.

So far my first concept is using the order-of-creation based on base-class constructor's being fired to determine which object is associated with what.

If I create a copy of a class (i.e. a Form-derived object), first the Form's constructor is fired, and then the constructor's of any class-based member-variables are fired. Is this a safe assumption? I imagine the only time this could be affected is by another thread creating the object of a Form or Control derivative?

If this assumption is true, I could save the 'this' pointer from the FormBase constructor, and then associate it with each Control via the base Control class' constructor? Then to ensure thread-safety, I could map the current FormBase pointer to the local thread id to ensure no conflict if multiply threads are creating forms at the same time?

I've created some mock-up code before trying to implement this into my main code. The following keeps track of the current Form being created by using a ThreadId-based map. When a control is created it gets the FormBase pointer based of it's ThreadId calling. The control then calls an Attach() function of it's parent Form using the pointer it just got, and parses a pointer to the control. The Form then adds the control's pointer to a list. When the Form eventually parses WM_CREATE, it automatically pulls the controls from the list and fires their virtual Create() functions to build them.

Mock-up:

Code:
#include <Windows.h>
#include <string>
#include <map>
#include <list>
class FormBase;// Forward declaration
class FormMap;// Forward declaration
class Object {};// Base Object

[Code] ....

Is this plausible to use? I imagine C++ does not have many "guarantees" about how it creates objects and when. But I thought it would be safe that it would never create member-variables before the class of them is first created?

View 2 Replies View Related

C++ :: Cannot Deduce Template Parameter For Integer

Sep 18, 2014

I have the defined a class Seconds with a template<int,int> constructor. Unfortunately, I can't seem to get an instance. Here's the class :

class Seconds {
public :
template <int num, int den> Seconds(long int);
}

And when I try to instantiate it :

Seconds *millis = new Seconds<1,1000>(30); // template argument deduction/substitution failed:
// couldn't deduce template parameter ‘num’

Is it not the right way to call the constructor?

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++ :: Partial Specialization Of Template Parameter

Nov 20, 2013

I've been trying to create a templated class that takes a template as a parameter. I'd like to specialise this class for certain partial specializations of the template parameter but can't seem to figure out how to do it nor find anything online, (although I may be searching for the wrong thing).

As an example, say I have a class A that takes a template class with two parameters as its parameter:

template< template<class X, class Y> class Z > class A {};

I'd like to have a general version of A, for a general version of Z, but a specialisation of A for a specialisation of Z, e.g. where X is int but Y is still any type.

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

Visual C++ :: Template Parameter Resolving To Nothing?

Apr 2, 2015

Is there an "easy" way to define a template with a template parameter that could resolve to "nothing".

Code:
template <typename T1, typename T2, typename T3>
struct one_to_three {
public:
T1 t1;
T2 t2;
T3 t3;
};

Now I want to be able to instantiate that in such a way that T3 and T2 (if T3 also) resolve to "nothing".

Don't point me at tuple<>, this has to be a single structure. No dummy's, nothing effectively means nothing.

so on Win32

Code:
one_to_three <int, int, int> x;
sizeof(x) == 12;
one_to_three <int, nothing, nothing> y; // whatever 'nothing' needs to be.
sizeof(y) == 4;

T1 will never be 'nothing'
T2 will only be 'nothing' if T3 also is 'nothing' (if it works with T3 not being nothing, that's fine, but it won't get used that way).

Portability is a non-issue, this only needs to work in VS (2010 and higher). The 'real' solution will need up to T10, I have a solution working with SFINAE, but it takes very very long to compile and it's getting very unwieldy if you would need to add T11.

I know it's not an ideal type approach, but it is what it is, this is a necessity due to linking with a legacy API which we don't have control over.

View 9 Replies View Related

C++ :: Pass By Reference To A Template Function Through Parameter Only

Sep 19, 2014

Due to the nature of this requirement, I've made a very minimal example, which would adequately solve my issue, without resorting to use of pointers or copy constructors.

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;

[Code] ....

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

View 1 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/C++ :: Get Return Type Of Function In Template Parameter

Jul 27, 2012

Is this really the preferred way to get the return type, for use in a derived class, of a function defined in the template parameter?

template<class PARAMETER> class C {
         protected:
            typedef typeof (reinterpret_cast<PARAMETER*>(0))->function() returntype;
      };  

This works just fine for me, but seems inelegant.

View 12 Replies View Related

C++ :: Program - Unique Values To Use As Template Parameter

Oct 14, 2014

I'm looking for a way to generate a program-wide unique value to use as a template parameter. Generating a unique value within a translation unit is pretty easy with __LINE__, but that doesn't ensure uniqueness across translation units. I thought maybe I could use __FILE__, but that can't be used as a template parameter.

I stumbled across this page: [uRL] ....

which is exactly what I want, except that the anonymous namespace trick doesn't work on all the compilers I've tried it on. (This may be due to C++11 changing anonymous namespaces to internal linkage rather than external as they did before....that page is five years old.)

View 8 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++ :: 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++ ::  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++ :: Use Of Class Template Requires Template Argument List

Nov 6, 2013

Error1error C2955: 'DoubleLinkedListInterface' : use of class template requires template argument listdoublelinkedlist.h10
Error2error C2244: 'DoubleLinkedList<T>::DoubleLinkedList' : unable to match function definition to an existing declaration doublelinkedlist.cpp7

Error3 .cpperror C2244: 'DoubleLinkedList<T>::~DoubleLinkedList' : unable to match function definition to an existing declaration 12

.h

#pragma once
#include "DoubleLinkedListInterface.h"
#include "Node.h"
#include <iostream>

[Code]....

View 4 Replies View Related

C++ :: Partial Template Specialization With Template Class

May 27, 2013

I have a generic template class with another template in one of its types. Now I want to specialize one of its methods for a particular (template) class, which leads to a compile error, however.

Here is the example:

#include <stdio.h>
template<typename Type>
class Obj1 {
public:
void ID() { printf("Object 1, size = %zu

[Code] .....

GCC ends with:
:35:27: error: type/value mismatch at argument 2 in template parameter list for ‘template<class Type, template<class> class O> class Foo’
:35:27: error: expected a class template, got ‘Obj2<Type>’

What is wrong with the specialization? Can it even be achieved and how (if so)?

View 1 Replies View Related

C++ :: Calling Derived Class Functions In A Function With Parameter Of Base Class

Mar 30, 2013

Say I have 3 classes:

class Player {
public:
virtual func1();

[code]....

Say in my main class, I have a function fight(Player p1, Player p2) and I would like to do something like this in the fight function, given that p1 is the human and p2 is the computer:

//function fight()
fight(Player p1, Player p2) {
p1.func2();
}
//using function fight()
fight(human, computer);

When I compile the program, I got this: error: ‘class Player’ has no member named 'func2()' What can I do to allow p1 to call func2 inside fight()? I'm not allowed to use pointers as the parameter for fight() and have to use the signature fight(Player p1, Player p2).

View 6 Replies View Related

C++ :: Using Child Class As Parameter Of A Function In Its Parent Class

Aug 27, 2014

I am currently having an issue with a piece of code that I am writing in which I need to use a vector of a child class as a parameter in a function in the parent class. Below is an example of my code:

#include "child.h"
#include <vector>
class parent {
parent();
function(std::vector<child> children);
// rest of class here
}

When I do this my program doesn't compile. However if I try to forward declare, as shown in the following example, it once again refuses to compile:

#include <vector>
class child;
class parent{
parent();
function(std::vector<child> children);
// rest of class here
}

This time, it refuses to compile because it needs to know the full size of the class child in order to create the vector. How to being able to access the child is essential for my program, so what should I do?

View 3 Replies View Related

C++ :: Template Class With Template Members

Feb 9, 2015

I have a class like this

PHP Code:
template<class X>
class A {
  X m_x;
public:
    X* foo();
    X* bar();
    //others are not related to X
}; 

I would like to get rid of

PHP Code: template<class X> 

For class level but still use it for members. Like this

PHP Code:
class A {
  X m_x;
public:
    template<class X>
    X* foo();
    template<class X>
    X* bar();
    //others are not related to X
}; 

However, I am still stuck at

PHP Code: X m_x; 

View 6 Replies View Related

C++ :: Declare Template Type Object Inside Template Type Class Definition

Oct 12, 2013

Let me put it into the code snippet:

/**
This class build the singleton design pattern.
Here you have full control over construction and deconstruction of the object.
*/
template<class T>
class Singleton

[Code]....

I am getting error at the assertion points when i call to the class as follows:

osgOpenCL::Context *cxt = osgOpenCL::Singleton<osgOpenCL::Context>::getPtr();

I tried commenting assertion statements and then the debugger just exits at the point where getPtr() is called.

View 7 Replies View Related

C++ :: How To Initialize Static Member Of Class With Template And Type Of Nested Class

Oct 7, 2014

How to initialize a static member of a class with template, which type is related to a nested class?

This code works (without nested class):

#include<iostream>
using namespace std;
struct B{
B(){cout<<"here"<<endl;}
};
template<typename Z>

[Code] ,....

View 1 Replies View Related

C/C++ :: Using Class Parameter In Virtual Class

Mar 27, 2015

I am trying to create a platformer and is stuck on a problem regarding my virtual class Entity. I wish to use it to create stuff like the Player and Enemy class(es). But how to do the parameter for my collision check function. Below is my Entity- and player class.

There might be a better way to check CC with a lot of different objects, this is my first attempt.

This is the error I am getting: "error C2664: 'bool Player::CollisionCheck(Hostile)' : cannot convert argument 1 from 'Player' to 'Hostile'"

#ifndef ENTITY_H
#define ENTITY_H
#include <SFMLGraphics.hpp>
class Entity {
public:
Entity();
Entity(sf::Vector2f position, sf::Vector2f size, sf::Color fillColor, sf::Color outlineColor);

[Code] ....

and in Hostile I would (I guess) use
bool CollisionCheck(Player p);

But if I try for example to use Player in the CC in player.h it will complain that the function doesn't have an overload for that. Hostile is just a example class name right now, it isn't implemented yet. I am trying to use Player, but if possible wish to be able to have a different class depending on what kind of entity it is. The entity will probably also be the players projectiles and so on.

View 1 Replies View Related

C++ ::  Template Class Inheriting A Templated Class

Dec 9, 2014

I'm making a minimal spanning tree class that inherits a graph class, both are templated. This is my mstree.h so far:

#ifndef _MSTREE_H_
#define _MSTREE_H_
#include "graph.h"
namespace MSTreeNameSpace

[Code]...

and I keep getting these errors:

mst.h:9:25: error: expected template-name before ‘<’ token
class MST : public Graph<T>
^
mst.h:9:25: error: expected ‘{’ before ‘<’ token
mst.h:9:25: error: expected unqualified-id before ‘<’ token

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







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