template of variadic template: parameter pack expects a type template - variadic-templates

template <typename T, template <typename T, typename... Targs> class C>
void print_(const C<T,Targs>& arg, std::stringstream& ss)
{
std::for_each(arg.begin(), arg.end(), [&ss](const T& var) { ss << var; });
}
int main()
{
vector<int> vec{1,2,3};
std::stringstream ss;
print_(vec,ss);
}
main.cpp(8): error C2065: 'Targs': undeclared identifier
main.cpp(8): error C3544: 'Targs': parameter pack expects a type template

Names that are part of a template parameters list introduced by a template template parameter are valid only within that list.
In other terms, something like this is legal:
template<template<typename T, T> class U>
struct S {};
And you can use it as it follows:
template<typename T, T>
struct A {};
template<template<typename T, T> class U>
struct B {};
int main() {
B<A> b;
}
This isn't valid code instead:
template <typename T, template <typename T, typename... Targs> class C>
void print_(const C<T,Targs> &, std::stringstream &);
Targs is no longer a valid name after the first > symbol (the one that follows immediately Targs itself).
The compiler keeps saying it to you quite clearly: undeclared identifier.
That being said, in your question there isn't an actual question, so I don't know what you expect from an answer but to tell you why that's an error.

this worked!
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
template <typename T, template <typename T, typename... > class C, class... Args>
void print_(std::stringstream& ss, const C<T,Args...>& arg)
{
std::for_each(arg.begin(), arg.end(), [&ss](const T& var) { ss << var << ":"; });
}
int main()
{
vector<int> vec{1,2,3};
std::stringstream ss;
print_(ss, vec);
cout << ss.str();
}

Related

I am not able to access private variables of class, I have used friend class

#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Movie
{
private:
std::string name{};
std::string rating{};
int watched{};
friend class movies;
public:
Movie(std::string name_val, std::string rating_val, int watched_val = 0);
// copy constructor
Movie(const Movie &source); //// this constructor
};
Movie::Movie(std::string name_val, std::string rating_val, int watched_val)
:name{name_val}, rating{rating_val}, watched{watched_val}{}
Movie::Movie(const Movie &source){
name = source.name;
rating = source.rating;
watched = source.watched;
}
class Movies
{
private:
std::vector<Movie> movie_obj;
public:
void get_movie_byname(Movie &abc) { std::cout << abc.name; }; // here is error abc.name
};
here is the error message
main.cpp:53:53: error: 'std::string Movie::name' is private within this context
53 | void get_movie_byname(Movie &abc) { std::cout << abc.name; };
| ^~~~
main.cpp:11:21: note: declared private here
11 | std::string name {};
| ^~~~
cant understand whats wrong...
i think friend of a class is friend of for given obj ( this--> ), and not for all obj,
if i removed copy constructor of Movie, error resolved!
cant understand relation between copy constructor and friend.
// issue solved turns out its just typo in Movies, declaration in friend declaration.

what is the correct syntax function pointer list with class member?

I have a list of function pointers, the non-class member compiles without errors, but the class member compiles with errors:
error: cannot convert 'void (CVdmConfig::)()' to 'fp {aka void ()()}' in initialization
CVdmConfig::writeConfig is a void function.
typedef void (*fp)();
fp fpList[] = {&valvesCalib,&CVdmConfig::writeConfig} ;
What do I wrong ?
best regards
Werner
Without seeing the rest of your code, there is not much I can debug, but here is an example that works:
#include <iostream>
using namespace std;
void valvesCalib() {
cout << "inside function\n";
}
class CVdmConfig {
public:
static void writeConfig() {
cout << "inside method\n";
}
};
typedef void (*fp)();
fp fpList[] = {
&valvesCalib,
&CVdmConfig::writeConfig
};
int main()
{
for (auto f: fpList) {
f();
}
return 0;
}
/*
Output:
inside function
inside method
Program finished with exit code 0
*/
The problem was the missing static definition in the member function. But this leads into other problems with variables in the class. So I use a wrapper for this.

Compile Errors in Class with User Defined Functions

I am trying to build a class that stores a user-defined function inside of it for later use. I have decided to use the boost::function object to do so.
However, I get the following error on compile:
error: no match for ‘operator=’ in ‘((SomeClass*)this)->SomeClass::someFunction = ((SomeClass*)this)->SomeClass::DefaultFunction’
I do not understand this error, since someFunction and DefaultFunction should, as far as I can see, have the same types.
The code is shown below:
#include <boost/function.hpp>
class SomeClass{
private:
boost::function<int(int)> someFunction;
int DefaultFunction(int i);
public:
SomeClass();
~SomeClass();
void SetFunction(int (*f)(int));
};
int SomeClass::DefaultFunction(int i){
return i+1;
}
SomeClass::SomeClass(){
someFunction=DefaultFunction;
}
~SomeClass::SomeClass(){
}
void SomeClass::SetFunction(int (*f)(int i)){
someFunction=f;
}
void MyProgram(){
SomeClass s;
}
Can anyone offer any pointers as to how to construct such an object? Alternatively, iff there is a better way than the one I am attempting, could you explain it to me?
Kindest regards!
DefaultFunction is a member function of SomeClass.
Member function is called for some instance of SomeClass.
This function takes "hidden" pointer to SomeClass instance as its first parameter addition to int.
So member function is not the same as free function.
Your someFunction is object of boost::function, so it is wrapper for callable object.
Your requirements to that object are: take int and returns int.
In order to assign DefaultFunction (as member function) to someFunction you need to create this callable object.
Here you need to specify for which instance of SomeClass this object will be called, to do that use boost::bind:
SomeClass::SomeClass(){
someFunction=boost::bind(&SomeClass::DefaultFunction, this, boost::placeholders::_1);
}
In the code above you create callable object which will behave as
struct unnamedClass {
SomeClass* sc;
unnamedClass (SomeClass* sc) : sc(sc) {} // here sc is this of SomeClass
int operator()(int arg)
{
return sc->DefaultFunction(arg);
}
};
so when you invoke someFunction(10) it takes 10 as argument and call DefaultFunction for current this instance.
This
void SomeClass::SetFunction(int (*f)(int i)){
someFunction=f;
}
works because f is free function, which takes no hidden - pointer to class instance.
Using the answer of #rafix07, the following code compiled:
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/bind/placeholders.hpp>
class SomeClass{
private:
public:
SomeClass();
~SomeClass();
boost::function<int(int)> someFunction;
int DefaultFunction(int i);
void SetFunction(int (*f)(int));
};
int SomeClass::DefaultFunction(int i){
return i+1;
}
SomeClass::SomeClass(){
someFunction=boost::bind(&SomeClass::DefaultFunction, this, _1);
}
SomeClass::~SomeClass(){
}
void SomeClass::SetFunction(int (*f)(int i)){
someFunction=f;
}
int MyOwnProgram(int i){
return i+2;
}
void MyProgram(){
SomeClass s;
std::cout<<s.someFunction(2)<<std::endl;
s.SetFunction(MyOwnProgram);
std::cout<<s.someFunction(2)<<std::endl;
}
int main()
{
MyProgram();
}
The output from the program is:
3
4

Linker generates undefined references derived templated class instance - code update with fix

I have the following abstract class -
#ifndef FOO_H
#define FOO_H
template <typename T>
class FOO{
public:
virtual void bar();
protected:
T foobar;
};
#endif
I then derive from this class -
#ifndef BAH_H
#define BAH_H
#include "foo.h"
template <typename T>
class BAH : public FOO<T>{
public:
BAH(){};
void bar(T const &);
};
#endif
////////////////////////////////////////////////
//Class Methods
////////////////////////////////////////////////
template<class T>
void BAH<T>::bar(T const &)
{
}
I then create main
#include "bah.h"
int main(int argc, char **argv)
{
FOO<int> *i_bah = new BAH<int>();
}
and on compilation % g++ main.cpp -I./
I now get -
/tmp/ccglncVU.o:(.rodata._ZTV3BAHIiE[vtable for BAH]+0x10): undefined reference to FOO<int>::bar()'
/tmp/ccglncVU.o:(.rodata._ZTV3FOOIiE[vtable for FOO<int>]+0x10): undefined reference toFOO::bar()'
collect2: ld returned 1 exit status

A program using class template, pair, vector

I'm trying to program the following:
A template class map having a pointer to a vector that contains elements std::pair<T,Q>, where T and Q are template types. It's supposed to work similarly to std::map and T is 'key' type, whereas Q stands for 'value' type. Besides the following should be implemented:
1. Constructor & destructor.
2. Function empty returning bool (if the object is empty).
3. Function size (using count_if)
4. Function clear that deletes all vector records.
5. Operator [] which allows for: map["PI_value"] = 3.14; It should use function find
6. Operators =, ==, !=, >> (using equal function)
I've been trying to code the above task, but have stuck on the code below.
Do you have any ideas to repair this mess?
#include <iostream>
#include <tuple>
#include <utility>
#include <algorithm>
#include <vector>
using namespace std;
template <typename T, typename Q>
class mapa
{
private:
vector<std::pair<T,Q>>* ptr;
public:
/**< DEFAULT CONSTRUCTOR/////////////////////////// */
mapa()
{
ptr = new vector<std::pair<T,Q>>;
ptr->push_back(std::pair<T,Q>(0,0));
}
/**< DESTRUCTOR////////////////////////////////////// */
~mapa(){ delete ptr;}
/**< EMPTY()////////////////////////////// */
bool empty()
{
if(ptr)
return false;
else
return true;
}
/**< SIZE()///////////////////////////////// */
int size()
{
return ptr->size();
}
/**< CLEAR()///////////////////////////////// */
void clear()
{
ptr->clear(ptr->begin(), ptr->end());
}
/**< OPERATOR[]/////////////////////////////////////////// */
vector<std::pair<T,Q>>* & operator[](T key)
{
auto ptr2 = ptr;
if(empty())
{
std::pair<T,Q> para;
para.first = key;
para.second = 0;
ptr2->push_back(para);
//ptr2->push_back(std::pair<T,Q>(key,0));
}
else
{
auto ptr2 = find_if( ptr->begin(), ptr->end(),
[](std::pair<T,Q> example,T key)
{
return(example.first==key);
}
);
}
return ptr2;
}
}; //class end
The lambda provided to std::find_if is declared wrong.
If you see e.g. this reference for std::find_if, you will see that the functions should be like
bool pred(const Type &a)
That means the lambda should be something like
[&key](const std:pair<T, Q>& element) { return element.first == key }
There are also other problems with your operator[] function, like that it should return Q& instead of a reference to the vector pointer. You should also remember that std::find_if returns an iterator to the found element, or end() if not found.