C++ functor binding - c++

i tried to use the old bind2nd function in this way:
template<typename T>
class printer
{
public:
void operator()(T a, string& kd)
{
cout<<a<<endl;
}
};
int main(int argc, char *argv[])
{
string nme = "J-dar";
auto f1 = bind2nd(printer<int>(),nme);
//f1(5);
return 0;
}
but i get a lot of errors:
required from here
error: no type named 'first_argument_type' in 'class printer<int>' class binder2nd ^
error: no type named 'second_argument_type' in 'class printer<int>' typename _Operation::second_argument_type value; ^
error: no type named 'second_argument_type' in 'class printer<int>' binder2nd(const _Operation& __x, ^
error: no type named 'result_type' in 'class printer<int>' operator()(const typename _Operation::first_argument_type& __x) const ^
error: no type named 'result_type' in 'class printer<int>' operator()(typename _Operation::first_argument_type& __x) const ^
required from here
error: no type named 'second_argument_type' in 'class printer<int>' typedef typename _Operation::second_argument_type _Arg2_type;
from what i can see it's all correct so i don't really know what is going on. ^

First of all: I would recommend using abandoning bind1st() and bind2nd(), which are deprecated in C+11, and in general the obsolete support for functional programming of the C++03 Standard Library.
You should rather use C++11's std::bind(), since it seems you can afford that - judging from the fact that you are using the auto keyword:
#include <functional>
// ...
auto f1 = std::bind(printer<int>(), std::placeholders::_1, nme);
This said, just for the record, the deprecated std::bind2nd() function requires some metadata about the signature of your functor's call operator, and it expects these metadata to be provided as type aliases in your functor class. For instance:
template<typename T>
class printer
{
public:
// These metadata must be present in order for bind1st and bind2nd to work...
typedef void result_type;
typedef T first_argument_type;
typedef string const& second_argument_type;
void operator()(T a, string const& kd) const
// ^^^^^ // Bonus advice #1:
// // This could and should be
// // const-qualified
// ^^^^^
// Bonus advice #2: why not taking by
// reference to const here? ;)
{
cout<<a<<endl;
}
};
A simpler way of achieving the above is to use the (also deprecated) class template std::binary_function as a base class, and let that class template define the appropriate type aliases:
template<typename T>
class printer : public std::binary_function<T, string const&, void>
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
public:
void operator()(T a, string const& kd) const
{
cout<<a<<endl;
}
};
But again, please consider putting std::bind1st(), std::bind2nd(), as well as std::unary_function and std::binary_function, back in the drawer. They are superseded by C++11's more powerful support for functional programming.

Related

operator== does not compile if I include <iostream>

The following code compiles perfectly if:
I don't include <iostream> or
I name operator== as alp::operator==.
I suppose there is a problem with <iostream> and operator==, but I don't know what.
I compile the code with gcc 7.3.0, clang++-6.0 and goldbolt. Always the same error.
The problem is that the compiler is trying to cast the parameters of operator== to const_iterator, but why? (I suppose the compiler doesn't see my version of operator==, and looks for other versions).
#include <vector>
#include <iostream> // comment and compile
namespace alp{
template <typename It_base>
struct Iterator {
using const_iterator = Iterator<typename It_base::const_iterator>;
operator const_iterator() { return const_iterator{}; }
};
template <typename It_base>
bool operator==(const Iterator<It_base>& x, const Iterator<It_base>& y)
{ return true;}
}// namespace
struct Func{
int& operator()(int& p) const {return p;}
};
template <typename It, typename View>
struct View_iterator_base{
using return_type = decltype(View{}(*It{}));
using const_iterator =
View_iterator_base<std::vector<int>::const_iterator, Func>;
};
using view_it =
alp::Iterator<View_iterator_base<std::vector<int>::iterator, Func>>;
int main()
{
view_it p{};
view_it z{};
bool x = operator==(z, p); // only compiles if you remove <iostream>
bool y = alp::operator==(z,p); // always compile
}
Error message:
yy.cpp: In instantiation of ‘struct View_iterator_base<__gnu_cxx::__normal_iterator<const int*, std::vector<int> >, Func>’:
yy.cpp:9:73: required from ‘struct alp::Iterator<View_iterator_base<__gnu_cxx::__normal_iterator<const int*, std::vector<int> >, Func> >’
yy.cpp:44:29: required from here
yy.cpp:28:42: error: no match for call to ‘(Func) (const int&)’
using return_type = decltype(View{}(*It{}));
~~~~~~^~~~~~~
yy.cpp:22:10: note: candidate: int& Func::operator()(int&) const <near match>
int& operator()(int& p) const {return p;}
^~~~~~~~
yy.cpp:22:10: note: conversion of argument 1 would be ill-formed:
yy.cpp:28:42: error: binding reference of type ‘int&’ to ‘const int’ discards qualifiers
using return_type = decltype(View{}(*It{}));
~~~~~~^~~~~~~
I've made a more minimal test case here: https://godbolt.org/z/QQonMG .
The relevant details are:
A using type alias does not instantiate a template. So for example:
template<bool b>
struct fail_if_true {
static_assert(!b, "template parameter must be false");
};
using fail_if_used = fail_if_true<true>;
will not cause a compile time error (if fail_if_used isn't used)
ADL also inspects template parameter classes. In this case, std::vector<int>::iterator is __gnu_cxx::__normal_iterator<const int*, std::vector<int> >, Func>, which has a std::vector<int> in it's template. So, operator== will check in the global namespace (always), alp (As alp::Iterator is in alp), __gnu_cxx and std.
Your View_iterator_base::const_iterator is invalid. View_iterator_base::const_interator::result_type is defined as decltype(Func{}(*std::vector<int>::const_iterator{})). std::vector<int>::const_iterator{} will be a vectors const iterator, so *std::vector<int>::const_iterator{} is a const int&. Func::operator() takes an int&, so this means that the expression is invalid. But it won't cause a compile time error if not used, for the reasons stated above. This means that your conversion operator is to an invalid type.
Since you don't define it as explicit, the conversion operator (To an invalid type) will be used to try and match it to the function parameters if they don't already match. Obviously this will finally instantiate the invalid type, so it will throw a compile time error.
My guess is that iostream includes string, which defines std::operator== for strings.
Here's an example without the std namespace: https://godbolt.org/z/-wlAmv
// Avoid including headers for testing without std::
template<class T> struct is_const { static constexpr const bool value = false; } template<class T> struct is_const<const T> { static constexpr const bool value = true; }
namespace with_another_equals {
struct T {};
bool operator==(const T&, const T&) {
return true;
}
}
namespace ns {
template<class T>
struct wrapper {
using invalid_wrapper = wrapper<typename T::invalid>;
operator invalid_wrapper() {}
};
template<class T>
bool operator==(const wrapper<T>&, const wrapper<T>&) {
return true;
}
}
template<class T>
struct with_invalid {
static_assert(!is_const<T>::value, "Invalid if const");
using invalid = with_invalid<const T>;
};
template<class T>
void test() {
using wrapped = ns::wrapper<with_invalid<T>>;
wrapped a;
wrapped b;
bool x = operator==(a, b);
bool y = ns::operator==(a, b);
}
template void test<int*>();
// Will compile if this line is commented out
template void test<with_another_equals::T>();
Note that just declaring operator const_iterator() should instantiate the type. But it doesn't because it is within templates. My guess is that it is optimised out (where it does compile because it's unused) before it can be checked to show that it can't compile (It doesn't even warn with -Wall -pedantic that it doesn't have a return statement in my example).

Map enum value to template argument in C++

I have an enum class with several members. The goal of the enum is to encode primitive types (e.g. int, long, float, ...) at runtime, so that it's possible to store this information in a database for example. At the same time a lot of classes templated to work on primitive types exist as well.
The problem: I want to create an object from such a templated class, given an enum value that is not a constant. Would this be possible in any way that is cleaner and more scalable than creating a long switch on the enum values (or doing essentially the same with a map as proposed in the answer of Dynamic mapping of enum value (int) to type)?
Here's something I've been trying hoping that template type inference could work, but it fails to compile (can be checked here for example: http://rextester.com/VSXR46052):
#include <iostream>
enum class Enum {
Int,
Long
};
template<Enum T>
struct EnumToPrimitiveType;
template<>
struct EnumToPrimitiveType<Enum::Int> {
using type = int;
};
template<>
struct EnumToPrimitiveType<Enum::Long> {
using type = long;
};
template<typename T>
class TemplatedClass
{
public:
TemplatedClass(T init): init{init} {}
void printSize() { std::cout << sizeof(init) << std::endl; }
private:
T init;
};
template<Enum T>
auto makeTemplatedClass(T enumValue) -> TemplatedClass<EnumToPrimitiveType<T>::type>
{
TemplatedClass<EnumToPrimitiveType<T>::type> ret(5);
return ret;
}
int main()
{
Enum value{Enum::Int};
auto tmp = makeTemplatedClass(value);
tmp.printSize();
}
Compile error:
source_file.cpp:36:27: error: expected ‘)’ before ‘enumValue’
auto makeTemplatedClass(T enumValue) -> TemplatedClass<EnumToPrimitiveType<T>::type>
^
source_file.cpp:36:6: warning: variable templates only available with -std=c++14 or -std=gnu++14
auto makeTemplatedClass(T enumValue) -> TemplatedClass<EnumToPrimitiveType<T>::type>
^
source_file.cpp:36:38: error: expected ‘;’ before ‘->’ token
auto makeTemplatedClass(T enumValue) -> TemplatedClass<EnumToPrimitiveType<T>::type>
^
source_file.cpp: In function ‘int main()’:
source_file.cpp:44:16: error: ‘A’ is not a member of ‘Enum’
Enum value{Enum::A};
^
source_file.cpp:45:34: error: missing template arguments before ‘(’ token
auto tmp = makeTemplatedClass(value);
^
Problems I see:
You cannot use template<Enum T> auto makeTemplatedClass(T enumValue) since T is not a type. You need to use just template<Enum T> auto makeTemplatedClass() and invoke the function differently.
You need to use TemplatedClass<typename EnumToPrimitiveType<T>::type> instead of just TemplatedClass<EnumToPrimitiveType<T>::type>. That is necessary since type is a dependent type.
You cannot use value as a template parameter unless it is a const or constexpr.
The following program compiles and builds on my desktop.
#include <iostream>
enum class Enum {
Int,
Long
};
template<Enum T>
struct EnumToPrimitiveType;
template<>
struct EnumToPrimitiveType<Enum::Int> {
using type = int;
};
template<>
struct EnumToPrimitiveType<Enum::Long> {
using type = long;
};
template<typename T>
class TemplatedClass
{
public:
TemplatedClass(T init): init{init} {}
void printSize() { std::cout << sizeof(init) << std::endl; }
private:
T init;
};
template<Enum T>
auto makeTemplatedClass() -> TemplatedClass<typename EnumToPrimitiveType<T>::type>
{
TemplatedClass<typename EnumToPrimitiveType<T>::type> ret(5);
return ret;
}
int main()
{
Enum const value{Enum::Int};
auto tmp = makeTemplatedClass<value>();
tmp.printSize();
}

C++: cannot access protected member from derived class

I have a class MyVariable that holds an object and does some extra work when this object has to be modified. Now I want to specialize this to MyContainer for container objects that perform this extra work only when the container itself is modified (e.g. via push_back()) but not its elements.
My code looks like this:
template<typename T>
class MyVariable
{
public:
//read-only access if fine
const T* operator->() const {return(&this->_element);}
const T& operator*() const {return( this->_element);}
//write acces via this function
T& nonconst()
{
//...here is some more work intended...
return(this->_element);
}
protected:
T _element;
};
template<typename T>
class MyContainer: public MyVariable<T>
{
public:
template<typename Arg>
auto nonconst_at(Arg&& arg) -> decltype(MyVariable<T>::_element.at(arg))
{
//here I want to avoid the work from MyVariable<T>::nonconst()
return(this->_element.at(arg));
}
};
#include <vector>
int main()
{
MyContainer<std::vector<float>> container;
container.nonconst()={1,3,5,7};
container.nonconst_at(1)=65;
}
However, with GCC4.7.2 I get an error that I cannot access _element because it is protected.
test1.cpp: In substitution of 'template<class Arg> decltype (MyVariable<T>::_element.at(arg)) MyContainer::nonconst_at(Arg&&) [with Arg = Arg; T = std::vector<float>] [with Arg = int]':
test1.cpp:39:25: required from here
test1.cpp:17:4: error: 'std::vector<float> MyVariable<std::vector<float> >::_element' is protected
test1.cpp:26:7: error: within this context
test1.cpp: In member function 'decltype (MyVariable<T>::_element.at(arg)) MyContainer<T>::nonconst_at(Arg&&) [with Arg = int; T = std::vector<float>; decltype (MyVariable<T>::_element.at(arg)) = float&]':
test1.cpp:17:4: error: 'std::vector<float> MyVariable<std::vector<float> >::_element' is protected
test1.cpp:39:25: error: within this context
test1.cpp: In instantiation of 'decltype (MyVariable<T>::_element.at(arg)) MyContainer<T>::nonconst_at(Arg&&) [with Arg = int; T = std::vector<float>; decltype (MyVariable<T>::_element.at(arg)) = float&]':
test1.cpp:39:25: required from here
test1.cpp:17:4: error: 'std::vector<float> MyVariable<std::vector<float> >::_element' is protected
test1.cpp:26:7: error: within this context
What's going on here?
The problem does seem to be specific to the use of decltype() - if I explicitly declare nonconst_at() to return T::value_type&, thus:
template<typename Arg>
typename T::value_type& nonconst_at(Arg&& arg)
then GCC 4.8.2 compiles it with no warnings or errors. That's fine for standard containers, but obviously doesn't help every situation.
Actually calling this->_element.at(arg) isn't a problem: I can omit the trailing return type and have the compiler infer it:
template<typename Arg>
auto& nonconst_at(Arg&& arg)
{
//here I want to avoid the work from MyVariable<T>::nonconst()
return this->_element.at(std::forward<Arg>(arg));
}
with just a warning (which disappears with -std=c++1y) and no errors. I still need the this->, because _element is a member of a dependent base class (thanks, Simple).
EDIT - additional workaround:
As you're only interested in the type of the return value of T::at(), you can use the decltype of calling it with any T you like, even a null pointer:
template<typename Arg>
auto nonconst_at(Arg&& arg) -> decltype(((T*)nullptr)->at(arg))
{
//here I want to avoid the work from MyVariable<T>::nonconst()
return this->_element.at(std::forward<Arg>(arg));
}
It's ugly, but it does seem to work.

Error while using boost::shared_ptr

I'm learning boost and smart pointers. During compilation I got an error, and I can't figure out what is it about. I don't understand what I am doing wrong. The problem is in constructor:
DefaultCreature(const Creature& def) : def_(def) {}
Here is my code:
#include <iostream>
#include <boost/smart_ptr.hpp>
using namespace std;
using namespace boost;
class Creature;
typedef shared_ptr<Creature> PCreature;
class Creature {
public:
Creature(const string& name) : name_(name) {}
const string& getName() const { return name_; }
private:
string name_;
};
class DefaultCreature {
public:
DefaultCreature(const Creature& def) : def_(def) {}
private:
PCreature def_;
};
int main() {
DefaultCreature factory(Creature("lion"));
return 0;
}
And an error:
exercise1.cpp: In constructor ‘DefaultCreature::DefaultCreature(const Creature&)’:
exercise1.cpp:20:52: error: no matching function for call to ‘boost::shared_ptr<Creature>::shared_ptr(const Creature&)’
exercise1.cpp:20:52: note: candidates are:
In file included from /usr/local/include/boost/shared_ptr.hpp:17:0,
from /usr/local/include/boost/smart_ptr.hpp:21,
from exercise1.cpp:2:
/usr/local/include/boost/smart_ptr/shared_ptr.hpp:472:14: note: template<class Ap> boost::shared_ptr::shared_ptr(Ap, typename boost::detail::sp_enable_if_auto_ptr<Ap, int>::type)
/usr/local/include/boost/smart_ptr/shared_ptr.hpp:472:14: note: template argument deduction/substitution failed:
/usr/local/include/boost/smart_ptr/shared_ptr.hpp: In substitution of ‘template<class Ap> boost::shared_ptr::shared_ptr(Ap, typename boost::detail::sp_enable_if_auto_ptr<Ap, int>::type) [with Ap = Creature]’:
exercise1.cpp:20:52: required from here
/usr/local/include/boost/smart_ptr/shared_ptr.hpp:472:14: error: no type named ‘type’ in ‘struct boost::detail::sp_enable_if_auto_ptr<Creature, int>’
/usr/local/include/boost/smart_ptr/shared_ptr.hpp:446:14: note: template<class Y> boost::shared_ptr::shared_ptr(std::auto_ptr<_Tp1>&)
/usr/local/include/boost/smart_ptr/shared_ptr.hpp:446:14: note: template argument deduction/substitution failed:
exercise1.cpp:20:52: note: types ‘std::auto_ptr<T>’ and ‘const Creature’ have incompatible cv-qualifiers
(...)
/usr/local/include/boost/smart_ptr/shared_ptr.hpp:339:5: note: boost::shared_ptr<T>::shared_ptr() [with T = Creature]
/usr/local/include/boost/smart_ptr/shared_ptr.hpp:339:5: note: candidate expects 0 arguments, 1 provided
/usr/local/include/boost/smart_ptr/shared_ptr.hpp:328:25: note: boost::shared_ptr<Creature>::shared_ptr(const boost::shared_ptr<Creature>&)
/usr/local/include/boost/smart_ptr/shared_ptr.hpp:328:25: note: no known conversion for argument 1 from ‘const Creature’ to ‘const boost::shared_ptr<Creature>&’
The argument to shared_ptr must be the address of a dynamically allocated object but the code is passing in a reference. Change to, for example:
class DefaultCreature {
public:
DefaultCreature(const Creature& def) : def_(new Creature(def)) {}
private:
PCreature def_;
};
or using boost::make_shared:
class DefaultCreature {
public:
DefaultCreature(const Creature& def) :
def_(boost::make_shared<Creature>(def)) {}
private:
PCreature def_;
};
If the instance of DefaultCreature is the only object that has access to the object being pointed to by def_ then there is no reason for it to be a boost::shared_ptr: use boost::scoped_ptr instead. See What C++ Smart Pointer Implementations are available? for a very useful overview of smart pointers.
However, from the posted code there appears to be no reason to be using pointers of any nature. Just store a Creature instance in DefaultCreature (Creature is copyable and there is no polymorphic requirement, based on the posted code).

Using a templated parameter's value_type

How is one supposed to use a std container's value_type?
I tried to use it like so:
#include <vector>
using namespace std;
template <typename T>
class TSContainer {
private:
T container;
public:
void push(T::value_type& item)
{
container.push_back(item);
}
T::value_type pop()
{
T::value_type item = container.pop_front();
return item;
}
};
int main()
{
int i = 1;
TSContainer<vector<int> > tsc;
tsc.push(i);
int v = tsc.pop();
}
But this results in:
prog.cpp:10: error: ‘T::value_type’ is not a type
prog.cpp:14: error: type ‘T’ is not derived from type ‘TSContainer<T>’
prog.cpp:14: error: expected ‘;’ before ‘pop’
prog.cpp:19: error: expected `;' before ‘}’ token
prog.cpp: In function ‘int main()’:
prog.cpp:25: error: ‘class TSContainer<std::vector<int, std::allocator<int> > >’ has no member named ‘pop’
prog.cpp:25: warning: unused variable ‘v’
I thought this was what ::value_type was for?
You have to use typename:
typename T::value_type pop()
and so on.
The reason is that the compiler cannot know whether T::value_type is a type of a member variable (nobody hinders you from defining a type struct X { int value_type; }; and pass that to the template). However without that function, the code could not be parsed (because the meaning of constructs changes depending on whether some identifier designates a type or a variable, e.g.T * p may be a multiplication or a pointer declaration). Therefore the rule is that everything which might be either type or variable and is not explicitly marked as type by prefixing it with typename is considered a variable.
Use the typename keyword to indicate that it's really a type.
void push(typename T::value_type& item)
typename T::value_type pop()
Here is a full implementation of the accepted answers above, in case it helps anyone.
#include <iostream>
#include <list>
template <typename T>
class C1 {
private:
T container;
typedef typename T::value_type CT;
public:
void push(CT& item) {
container.push_back(item);
}
CT pop (void) {
CT item = container.front();
container.pop_front();
return item;
}
};
int main() {
int i = 1;
C1<std::list<int> > c;
c.push(i);
std::cout << c.pop() << std::endl;
}
A fairly common practice is to provide an alias representing the underlying value type for convenience.
template <typename T>
class TSContainer {
private:
T container;
public:
using value_type = typename T::value_type;
void push(value_type& item)
{
container.push_back(item);
}
value_type pop()
{
value_type item = container.pop_front();
return item;
}
};