This first piece has been solved by Eric's comments below but has led onto a secondary issue that I describe after the horizontal rule. Thanks Eric!
I'm trying to pass a functor that is a templated class to the create_thread method of boost thread_group class along with two parameters to the functor. However I can't seem to get beyond my current compile error. With the below code:
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/thread.hpp>
#include <vector>
using namespace boost::lambda;
using namespace std;
namespace bl = boost::lambda;
template<typename ftor, typename data>
class Foo
{
public:
explicit Foo()
{
}
void doFtor ()
{
_threads.create_thread(bind(&Foo<ftor, data>::_ftor, _list.begin(), _list.end()));
//_threads.create_thread(bind(_ftor, _list.begin(), _list.end()));
_threads.join_all();
}
private:
boost::thread_group _threads;
ftor _ftor;
vector<data> _list;
};
template<typename data>
class Ftor
{
public:
//template <class Args> struct sig { typedef void type; }
explicit Ftor () {}
void operator() (typename vector<data>::iterator &startItr, typename vector<data>::iterator &endItr)
{
for_each(startItr, endItr, cout << bl::_1 << constant("."));
}
}
I also tried typedef-ing 'type' as I thought my problem might have something to do with the Sig Template as the functor itself is templated.
The error I am getting is:
error: no matching function for call to ‘boost::lambda::function_adaptor<Ftor<int> Foo<Ftor<int>, int>::*>::apply(Ftor<int> Foo<Ftor<int>, int>::* const&, const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int>> >&, const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&)’
with a bunch of preamble beforehand.
Thanks in advance for any help!
Okay I've modified the code taking in Eric's suggestions below resulting in the following code:
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/thread.hpp>
#include <vector>
using namespace boost::lambda;
using namespace std;
namespace bl = boost::lambda;
template<typename ftor, typename data>
class Foo
{
public:
explicit Foo()
{
}
void doFtor ()
{
_threads.create_thread(bl::bind(boost::ref(_ftor), _list.begin(), _list.end()));
_threads.join_all();
}
private:
boost::thread_group _threads;
ftor _ftor;
vector<data> _list;
};
template<typename data>
class Ftor
{
public:
typedef void result_type;
explicit Ftor () {}
result_type operator() (typename vector<data>::iterator &startItr, typename vector<data>::iterator &endItr)
{
for_each(startItr, endItr, cout << bl::_1 << constant("."));
return ;
}
};
However this results in another compile error:
/usr/local/include/boost/lambda/detail/function_adaptors.hpp:45: error: no match for call to ‘(Ftor<int>) (const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&, const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&)’
ftor.h:41: note: candidates are: void Ftor<data>::operator()(typename std::vector<data, std::allocator<_CharT> >::iterator&, typename std::vector<data, std::allocator<_CharT> >::iterator&) [with data = int]
/usr/local/include/boost/lambda/detail/function_adaptors.hpp:45: error: return-statement with a value, in function returning 'void'
It seems having defined void as a result_type it is now expecting the operator() to return something. I tried returning result_type from within the function but this also generated errors. Any ideas?
Sig (or in your case, simply typedef void result_type; is necessary.
IIRC, lambda::bind makes const copies of its arguments.
There is thus a problem with functors with non-const operator(). This is solved by making Ftor::operator()const or by wrapping (in doFtor()), _ftor with boost::ref
There is a similar problem with the iterators. Wrapping in boost::ref here won't work directly because it would end up using a reference to a temporary. The simpler solution is to modify Ftor::operator() to take its arguments by copy.
The simplest is thus to modify Ftor so that its operator() is const and it takes its arguments by copy:
void operator() (typename vector<data>::iterator startItr, typename vector<data>::iterator endItr)const
If you really can't make Ftor::operator() const, you could modify doFtor() as follows (but it is still necessary to make Ftor::operator() take its arguments by copy):
_threads.create_thread(bind(boost::ref(_ftor), _list.begin(), _list.end()));
Related
Consider the following example
#include <iostream>
#include <any>
#include <vector>
#include <map>
#include <typeinfo>
typedef enum TYPE{
INT8=0,
INT16=1,
INT32=2
} TYPE;
int main()
{
std::map<TYPE, std::any> myMap;
myMap[TYPE::INT8] = (int8_t)0;
myMap[TYPE::INT16] = (int16_t)0;
myMap[TYPE::INT32] = (int32_t)0;
std::vector<decltype(myMap[TYPE::INT8])> vec;
}
I have a map in this example, going from some enum to std::any. I actually need a flexible data structure that can map from a specific type (enum TYPE in this case), to multiple data types (different types of int), hence the use of std::any.
Going ahead, I would like to ascertain the type of value given for the key and construct a vector with it. I tried the above code, and it runs into a compilation error because decltype will return std::any(correctly so).
I would want to extract the "true type" from the std::any and create that type of vector. How would I achieve that.
A small snippet of the compilation error is as follows -
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/new_allocator.h:63:26: error: forming pointer to reference type 'std::any&'
63 | typedef _Tp* pointer;
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/new_allocator.h:112:7: error: forming pointer to reference type 'std::any&'
112 | allocate(size_type __n, const void* = static_cast<const void*>(0))
/opt/compiler-explorer/gcc-12.2.0/include/c++/12.2.0/bits/stl_vector.h:1293:7: error: 'void std::vector<_Tp, _Alloc>::push_back(value_type&&) [with _Tp = std::any&; _Alloc = std::allocator<std::any&>; value_type = std::any&]' cannot be overloaded with 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::any&; _Alloc = std::allocator<std::any&>; value_type = std::any&]'
1293 | push_back(value_type&& __x)
TIA
As suggested in the comments by #Ted Lyngmo, I think std::variant serves you better. Especially with C++-20's templated lambdas, the std::visit function can work wonders with these to get around the awkwardness of dealing with type enums and the like.
Note that you can not get around the runtime type detection. In any case, here is an example of how it can work.
#include <cstdint>
#include <iostream>
#include <variant>
#include <vector>
using VariantScalar = std::variant<
std::int8_t, std::int16_t, std::int32_t>;
using VariantVector = std::variant<
std::vector<std::int8_t>,
std::vector<std::int16_t>,
std::vector<std::int32_t>>;
VariantVector fill_vector(VariantScalar scalar, std::size_t n)
{
auto make_vector = [n]<class IntType>(IntType v) -> VariantVector {
return std::vector<IntType>(n, v);
};
return std::visit(make_vector, scalar);
}
void print_vector(const VariantVector& vec)
{
std::visit([]<class T>(const std::vector<T>& vec) {
for(const T& s: vec)
std::cout << s << ' ';
std::cout << '\n';
}, vec);
}
int main()
{
VariantScalar s(std::int8_t(1));
VariantVector vec = fill_vector(s, 5);
print_vector(vec);
}
Assuming you have the following enum definition:
enum class TYPE{
INT8=0,
INT16=1,
INT32=2
};
Then you can define a helper:
template <TYPE>
struct my_type {}; // Base case
template <>
struct my_type<TYPE::INT8> {
using type = int8_t;
};
template <>
struct my_type<TYPE::INT16> {
using type = int16_t;
};
template <>
struct my_type<TYPE::INT32> {
using type = int32_t;
};
template <TYPE t>
using my_type = typename my_type<t>::type;
That you can use for your vector
std::vector<my_type<TYPE::INT8>> vec;
I am trying to pass a callback function as function parameter. But getting template substitution failure errors in following code. Not sure why template substitution is failing.
#include<iostream>
#include <map>
#include <tuple>
#include <functional>
template<typename A,typename B>
void myfun(std::map<A,B> & mm, std::function<std::tuple<A,B>(void)> fn)
{
A key;
B val;
std::tie(key,val) = fn();
mm[key] = val;
}
std::tuple<std::string,int> fun()
{
return std::make_tuple(std::string("hi"),1);
}
int main()
{
std::map<std::string,int> gg;
#if 0
//fixed version
std::function<std::tuple<std::string,int>(void)> yy = fun;//fixed
myfun(gg,yy);//fixed
#else
// error causing code
myfun(gg,fun);
#endif
}
And error is as following
main.cpp:8:6: note: template argument deduction/substitution failed:
main.cpp:25:17: note: mismatched types 'std::function<std::tuple<_T1, _T2>()>' and 'std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> (*)()'
myfun(gg,fun);
The compiler can't both cast to a std::function and deduce the template arguments. It doesn't understand the mapping between an arbitrary function pointer and a std::function.
There are a few ways round this.
You could explicitly create a std::function at the call site:
myfun(gg,std::function<std::tuple<std::string,int>(void)>{fun});`
You could write a make_function function to deduce the types for you. You can find discussions and implementations of this online, such as here, here and here.
myfun(gg,make_function(fun));
You could just forget about std::function and deduce the entire function type. This is the approach I would take:
template<typename A,typename B, typename Fun>
void myfun(std::map<A,B> & mm, Fun fn)
{
A key;
B val;
std::tie(key,val) = fn();
mm[key] = val;
}
I am having a problem in some code using type_traits from boost.
It is quite a complex part of the code, but I could isolate the part that gives the compilation error:
template<const size_t maxLen>
class MyString {
public:
typedef boost::conditional<(maxLen > 0), char[maxLen+1], std::string> ObjExternal;
};
template <class T>
class APIBase {
public:
typedef T obj_type;
typedef typename T::ObjExternal return_type;
};
template <class T>
int edit(const T& field, const typename T::return_type& value)
{
return 0;
}
int myFunction()
{
APIBase<MyString<10> > b;
char c[11];
return edit(b, c);
}
This gives the following error:
test.cpp: In function ‘int myFunction()’:
tes.cpp:109: error: no matching function for call to ‘edit(APIBase >&, char [11])’
tes.cpp:100: note: candidates are: int edit(const T&, const typename T::return_type&) [with T = APIBase >]
However, if I change the line with the code
char c[11];
by
MyString<10>::ObjExternal c;
it works. Similarly, if instead I change the line
typedef boost::conditional<(maxLen > 0), char[maxLen+1], std::string> ObjExternal;
by
typedef char ObjExternal[maxLen+1];
it also works. I am thinking that it is a problem with boost::conditional, as it seems it is not being evaluated right. Is there a problem in my code, or there is an alternative that can be used instead of boost::conditional to have this functionality?
I am thinking about using the 2nd option, but then I could not use maxLen as 0.
You need to use the member typedef type provided by conditional and not the conditional type itself.
Change:
typedef boost::conditional<(maxLen > 0),
char[maxLen+1],
std::string> ObjExternal;
to:
typedef typename boost::conditional<(maxLen > 0),
char[maxLen+1],
std::string>::type ObjExternal;
I am trying to create a callback registration class tat allows registration of callbacks against string identifier for different types. Each callback has the signature void function( T val ) where T is the changing type.
I have created the following base registrar class that maps strings to functions.
#include <string>
#include <map>
#include <functional>
#include <cstdint>
#include <iostream>
using namespace std;
template< typename ValueType >
class BasicConfigCallbackRegistrar
{
public:
typedef ValueType value_type;
typedef BasicConfigCallbackRegistrar< value_type > type;
typedef function< void( const value_type ) > signature_type;
typedef map< string, signature_type > callback_map_type;
/// #brief constructor
BasicConfigCallbackRegistrar() : callbackMap_()
{
}
/// #brief register a create callback
/// #param nodePath the path identifying the node in config database
/// #param callback the callback to register
type& RegisterCallback( string nodePath, signature_type callback )
{
callbackMap_.insert( make_pair( move(nodePath), callback ) );
return *this;
}
void MakeCallback( const string& nodePath, value_type val )
{
// no checking assumes item is in map,
// do not do this in production code
auto iter = callbackMap_.find( nodePath );
iter->second( val );
}
private:
callback_map_type callbackMap_; ///< the callback map
};
I then use variadic templates to create a derived class for each of the types I want to support.
template< typename... Types >
class ConfigCallbackRegistrar : public BasicConfigCallbackRegistrar<Types>...
{
public:
/// #brief constructor
ConfigCallbackRegistrar() : BasicConfigCallbackRegistrar<Types>()...
{}
};
This is then typedefed as:
typedef ConfigCallbackRegistrar< uint32_t, string > CallbackRegistrar;
When I try to use this class as follows:
struct UintFtor
{
void operator()( uint32_t val )
{
cout << val << "\n";
}
};
struct StringFtor
{
void operator ()( string val )
{
cout << val << "\n";
}
};
int main()
{
CallbackRegistrar registrar{};
registrar.RegisterCallback( "SomeNode", UintFtor() );
registrar.RegisterCallback( "SomeNode", StringFtor() );
return 0;
}
Unfortunately when I try to compile this I get the following ambiguity errors:
variadic-wrap.cpp: In function ‘int main()’:
variadic-wrap.cpp:87: error: request for member ‘RegisterCallback’ is ambiguous
variadic-wrap.cpp:27: error: candidates are: BasicConfigCallbackRegistrar<ValueType>& BasicConfigCallbackRegistrar<ValueType>::RegisterCallback(std::string, std::function<void(ValueType)>) [with ValueType = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]
variadic-wrap.cpp:27: error: BasicConfigCallbackRegistrar<ValueType>& BasicConfigCallbackRegistrar<ValueType>::RegisterCallback(std::string, std::function<void(ValueType)>) [with ValueType = unsigned int]
variadic-wrap.cpp:88: error: request for member ‘RegisterCallback’ is ambiguous
variadic-wrap.cpp:27: error: candidates are: BasicConfigCallbackRegistrar<ValueType>& BasicConfigCallbackRegistrar<ValueType>::RegisterCallback(std::string, std::function<void(ValueType)>) [with ValueType = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]
variadic-wrap.cpp:27: error: BasicConfigCallbackRegistrar<ValueType>& BasicConfigCallbackRegistrar<ValueType>::RegisterCallback(std::string, std::function<void(ValueType)>) [with ValueType = unsigned int]
Calls to MakeCallback which takes a parameter of type value_type also produce the same ambiguity error.
How can I resolve this without an explicit cast of registrar to the base class type?
I have a solution. All tat is needed is an extra level of indirection. In the Derived class I added a template function that dispatches to the correct base, as follows:
template< typename... Types >
class ConfigCallbackRegistrar : public BasicConfigCallbackRegistrar<Types>...
{
typedef ConfigCallbackRegistrar<Types...> type;
public:
/// #brief constructor
ConfigCallbackRegistrar() : BasicConfigCallbackRegistrar<Types>()...
{}
template<typename T>
type& Register( string nodePath,
typename BasicConfigCallbackRegistrar<T>::signature_type callback )
{
BasicConfigCallbackRegistrar<T>::RegisterCallback( std::move(nodePath),
std::move(callback) );
return *this;
}
};
The calling code becomes:
int main()
{
CallbackRegistrar registrar{};
registrar.Register<uint32_t>( "SomeNode", UintFtor() );
registrar.Register<string>( "SomeNode", StringFtor() );
return 0;
}
I'm trying to use boost::mpl::inherit_linearly to compose a container class using types provided by the user:
#include <typeinfo>
#include <iostream>
#include <vector>
#include <boost/mpl/inherit.hpp>
#include <boost/mpl/inherit_linearly.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/vector.hpp>
namespace mpl = ::boost::mpl;
//////////////////////////////////////////////
// Create the container by chaining vectors
//////////////////////////////////////////////
struct Base {};
// Types provided by the user
typedef mpl::vector<int, char, double>::type myTypes;
typedef mpl::inherit_linearly<
myTypes,
mpl::inherit<mpl::_1, std::vector<mpl::_2> >,
Base
>::type InheritedContainer;
// Function for accessing containers
template <typename T>
inline std::vector<T>& get_container(Base& c) {
return static_cast<std::vector<T>& >(c);
}
// Some functions that manipulate the containers
// NB: These functions only know about the Base and the types
// they want to access
void my_int_func(Base& b) {
get_container<int>(b).push_back(42);
}
void my_char_func(Base& b) {
get_container<char>(b).push_back('c');
}
int main() {
InheritedContainer container;
Base& bref = container;
my_int_func(bref);
std::cout << "Int: " << get_container<int>(bref).back() << std::endl;
my_char_func(bref);
std::cout << "Char: " << get_container<char>(bref).back() << std::endl;
return 0;
}
The compile error I get is:
question.cpp: In function ‘std::vector<T, std::allocator<_CharT> >& get_container(Base&) [with T = int]’:
question.cpp:40: instantiated from here
question.cpp:31: error: invalid static_cast from type ‘Base’ to type ‘std::vector<int, std::allocator<int> >&’
question.cpp: In function ‘std::vector<T, std::allocator<_CharT> >& get_container(Base&) [with T = char]’:
question.cpp:44: instantiated from here
question.cpp:31: error: invalid static_cast from type ‘Base’ to type ‘std::vector<char, std::allocator<char> >&’
Shouldn't Base be a base of whatever type is produced by inherit_linearly? And if so, shouldn't a vector<int> and the other vectors show up in the type hierarchy for static_cast to pull out?
Is there any other way to get this functionality?
I think Base is a base class of InheritedContainer, but not of
std::vector<int>.
As we know, std::vector isn't defined as the following:
class vector : Base {...
You may expect the following inheritance:
class InheritedContainer : Base, std::vector<int>, ... {...
However, in this case, the cast from Base to vector<int> is a cross-cast,
so this cannot be done with static_cast.
As you may know, the following is allowed:
InheritedContainer container;
Base& bref = container;
InheritedContainer& iref = static_cast<InheritedContainer&>(bref);
std::vector<int>& vi = iref;
std::vector<char>& vc = iref;
If you can prepare get_container, my_int_func and my_char_func, probably the types
to which the std::vector will be specialized are known beforehand.
If so, I suppose it is pertinent to hold InheritedContainer& instead of Base&
all along.
If you have to cast Base to vector<T>, probably
RTTI(for example adding virtual function to Base) and dynamic_cast will enable
the cast.