Determininig Class Types - c++

I am trying following code from book C++ Template The Complete Guide , but it is failing to compile with Visual Studio 2010.
template < typename T>
class IsClassType {
private:
typedef char One;
typedef struct { char a[2]; } Two;
template<typename C> static One test(int C::*);
template<typename C> static Two test(...);
public:
enum { Yes = sizeof ( IsClassType<T>::test<T>(0)) == 1 };
enum { No = !Yes };
};
template < typename T>
void check() {
if ( IsClassType<T>::Yes ) {
std::cout << " IsClassType Yes " << std::endl;
} else {
std::cout << " IsClassType No " << std::endl;
}
}
int main() {
std::cout << "Int: ";
check<int>();
}
Following is the compiler error.
1>------ Build started: Project: test123, Configuration: Debug Win32 ------
1> test123.cpp
1>e:\svn\office_expt\test123\test123\test123.cpp(45): error C2783: 'IsClassType<T>::Two IsClassType<T>::test(...)' : could not deduce template argument for 'C'
1> with
1> [
1> T=int
1> ]
1> e:\svn\office_expt\test123\test123\test123.cpp(42) : see declaration of 'IsClassType<T>::test'
1> with
1> [
1> T=int
1> ]
1> e:\svn\office_expt\test123\test123\test123.cpp(51) : see reference to class template instantiation 'IsClassType<T>' being compiled
1> with
1> [
1> T=int
1> ]
1> e:\svn\office_expt\test123\test123\test123.cpp(60) : see reference to function template instantiation 'void check<int>(void)' being compiled
1>e:\svn\office_expt\test123\test123\test123.cpp(45): error C2784: 'IsClassType<T>::One IsClassType<T>::test(int C::* )' : could not deduce template argument for 'int C::* ' from 'int'
1> with
1> [
1> T=int
1> ]
1> e:\svn\office_expt\test123\test123\test123.cpp(41) : see declaration of 'IsClassType<T>::test'
1> with
1> [
1> T=int
1> ]
1>e:\svn\office_expt\test123\test123\test123.cpp(45): error C2056: illegal expression
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Is it this line:
template<typename C> static Two test(...);
The typename cannot be inferred from this. I think it should read:
static Two test(...);

Related

How to fix custom allocator compiling error for std::map on windows?

I tried one here. Code as following:
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <new>
#include <climits>
namespace test {
template <class T>
inline T* _allocate(ptrdiff_t size, T*) {
std::cout << "_allocate called" << std::endl;
T* tmp = (T*)(::operator new((size_t)(size * sizeof(T))));
if (NULL == tmp) {
std::cerr << "out of memory" << std::endl;
exit(0);
}
return tmp;
}
template <class T>
inline void _deallocate(T* p) {
::operator delete(p);
}
template <class T1, class T2>
inline void _construct(T1* p, const T2& value) {
::new (p) T1(value);
}
template <class T>
inline void _destroy(T* p) {
p->~T();
}
template <class T>
class Allocator {
public:
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
template <class U>
struct rebind {
typedef Allocator<U> other;
};
pointer allocate(size_type n, const void* hint = 0) { return _allocate((difference_type)n, (pointer)0); }
void deallocate(pointer p, size_type n) { return _deallocate(p); }
void construct(pointer p, const T& value) { _construct(p, value); }
void destroy(pointer p) { _destroy(p); }
pointer address(reference x) { return (pointer)&x; }
const_pointer address(const_reference x) { return (const_pointer)&x; }
size_type max_size() const { return size_type(UINT_MAX / sizeof(T)); }
};
} // namespace test
static std::map<void*, uint64_t, std::less<void*>, test::Allocator<std::pair<void* const, uint64_t>>> global_map;
int main()
{
std::vector<std::string> vec = {
"Hello", "from", "GCC", "!"
};
std::cout << "xxxx " << global_map.size() << std::endl;
}
But it leads to compiling fail on Visual Studio 2019 x86:
Build started...
1>------ Build started: Project: ConsoleApplication1, Configuration: Debug Win32 ------
1>ConsoleApplication1.cpp
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30037\include\xtree(1096,27): error C2440: 'static_cast': cannot convert from 'test::Allocator<U>' to 'test::Allocator<U>'
1> with
1> [
1> U=std::_Tree_node<std::pair<void *const ,uint64_t>,void *>
1> ]
1> and
1> [
1> U=std::_Container_proxy
1> ]
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30037\include\xtree(1096,27): message : No constructor could take the source type, or constructor overload resolution was ambiguous
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30037\include\xtree(1092): message : while compiling class template member function 'std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::~_Tree(void) noexcept'
1> with
1> [
1> _Kty=void *,
1> _Ty=uint64_t,
1> _Pr=std::less<void *>,
1> _Alloc=test::Allocator<std::pair<void *const ,uint64_t>>
1> ]
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30037\include\map(348): message : see reference to function template instantiation 'std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::~_Tree(void) noexcept' being compiled
1> with
1> [
1> _Kty=void *,
1> _Ty=uint64_t,
1> _Pr=std::less<void *>,
1> _Alloc=test::Allocator<std::pair<void *const ,uint64_t>>
1> ]
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30037\include\map(75): message : see reference to class template instantiation 'std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>' being compiled
1> with
1> [
1> _Kty=void *,
1> _Ty=uint64_t,
1> _Pr=std::less<void *>,
1> _Alloc=test::Allocator<std::pair<void *const ,uint64_t>>
1> ]
How to fix it?
Edit:
Found another solution. But do not know why. Code as https://godbolt.org/z/jvscsMx7T
This problem appeard in Visual Studio Debug mode , but solved when switching to Release mode. If it still bothers you, you can report problems to Developer Community.

Call member method of a variadic class template with a member field

I learned a bit about variadic templates and searched over the Internet for some samples and now trying to write some tricky code to call member a method of a variadic class template with one of its fields. I can't understand why it doesn't work. Please, help.
Here is sample classes:
class BarBase
{
public:
BarBase() = default;
virtual void call() = 0;
};
template<typename O, typename M, typename... A>
class Bar
: public BarBase
{
public:
Bar(O* o, M m, A&&... a)
: BarBase()
, m_o(o), m_m(m), m_a(std::forward<A>(a)...)
{ }
void call() override final
{
callInnerWithArgsInside();
}
private:
void callInnerWithArgsInside()
{
(m_o->*m_m)(m_a); // Some errors happends here
}
O* m_o;
M m_m;
std::tuple<typename std::remove_reference<A>::type...> m_a;
};
template<typename O, typename M, typename... A>
BarBase* crateBar(O* o, M m, A&&... a)
{
return new Bar<O, M, A...>(o, m, std::forward<A>(a)...);
}
And call from main:
struct Foo
{
void foo(int ii, float ff, std::string ss)
{
std::cout << "called" << std::endl;
}
};
int main()
{
Foo f;
int i = 10;
float ff = 20.2f;
std::string s = "Hello";
BarBase* bar = crateBar(&f, &Foo::foo, i, ff, s);
bar->call();
}
Errors:
main.cpp
1>d:\drafts_tests\main.cpp(203): error C2198: 'void (__thiscall Foo::* )(int,float,std::string)' : too few arguments for call
1> d:\drafts_tests\main.cpp(202) : while compiling class template member function 'void Bar::callInnerWithArgsInside(void)'
1> with
1> [
1> O=Foo
1> , M=void (__thiscall Foo::* )(int,float,std::string)
1> ]
1> d:\drafts_tests\main.cpp(197) : see reference to function template instantiation 'void Bar::callInnerWithArgsInside(void)' being compiled
1> with
1> [
1> O=Foo
1> , M=void (__thiscall Foo::* )(int,float,std::string)
1> ]
1> d:\drafts_tests\main.cpp(214) : see reference to class template instantiation 'Bar' being compiled
1> with
1> [
1> O=Foo
1> , M=void (__thiscall Foo::* )(int,float,std::string)
1> ]
1> d:\drafts_tests\main.cpp(225) : see reference to function template instantiation 'BarBase *crateBar(O *,M,int &,float &,std::string &)' being compiled
1> with
1> [
1> O=Foo
1> , M=void (__thiscall Foo::* )(int,float,std::string)
1> ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
you are passing a tuple to the function, rather than the individual type arguments. The following will pass the required type args to the call:
template<std::size_t... I>
void callInnerWithArgsInside2(std::index_sequence<I...>)
{
(m_o->*m_m)(std::get<I>(m_a)...);
}
void callInnerWithArgsInside()
{
return callInnerWithArgsInside2( std::make_index_sequence<sizeof...(A)>());
}
live demo
EDIT1: C++11 version
I have implemented a C++11 version, see updated live demo

Error on compiling template function of Queue of std::functions

I want to make a template function to queue both general functions and also class member functions. With internet search, I came up with the following code but have error in compiling it.
#include <iostream>
#include <functional>
#include <queue>
#include <string>
double MyFunction(double num1, double num2)
{
std::cout << "MyFunction( " << num1 << ", " << num2 << " )\n";
return num1 + num2;
}
class MyClass
{
public:
double MyClassFunction(double num1, double num2, double num3) const
{
std::cout << "MyClass::MyClassFunction( " << num1 << ", " << num2 << ", " << num3 << " )\n";
return num1 + num2 + num3;
}
};
struct MyFunctionQueue
{
template <typename FUNC, typename... ARGS>
void QueueFunction(FUNC fn, ARGS&&... args)
{
std::function<std::result_of_t<FUNC(ARGS...)> () > rFunc = std::bind(fn, args...);
_myFQ.push(rFunc);
}
void Execute()
{
while (!_myFQ.empty())
{
_myR.push(_myFQ.front()());
_myFQ.pop();
}
}
double PopResult()
{
double r = _myR.front();
_myR.pop();
return r;
}
std::queue<std::function<double()>> _myFQ;
std::queue<double> _myR;
};
int main()
{
MyFunctionQueue funcQue;
funcQue.QueueFunction(MyFunction, 1.234, 2.345);
MyClass obj;
funcQue.QueueFunction(&MyClass::MyClassFunction, std::ref(obj), 1.234, 2.345, 3.456);
funcQue.Execute();
std::cout << "MyFunction result: " << funcQue.PopResult() << std::endl;
std::cout << "MyClass::MyClassFunction result: " << funcQue.PopResult() << std::endl;
}
I know the error is with the template code generation on the class member function. With my limited knowledge in using templates I cannot figure out what's wrong with it. Can anyone help to point out the mistake in the code? And the error I've got from VC++ is:
1>------ Build started: Project: TestFunctionQueue, Configuration: Debug Win32 ------
1> TestFunctionQueue.cpp
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\type_traits(1469): error C2672: 'std::invoke': no matching overloaded function found
1> c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(31): note: see reference to class template instantiation 'std::result_of<FUNC (std::reference_wrapper<MyClass>,double,double,double)>' being compiled
1> with
1> [
1> FUNC=double (__thiscall MyClass::* )(double,double,double) const
1> ]
1> c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(63): note: see reference to function template instantiation 'void MyFunctionQueue::QueueFunction<double(__thiscall MyClass::* )(double,double,double) const,std::reference_wrapper<MyClass>,double,double,double>(FUNC,std::reference_wrapper<MyClass> &&,double &&,double &&,double &&)' being compiled
1> with
1> [
1> FUNC=double (__thiscall MyClass::* )(double,double,double) const
1> ]
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\type_traits(1469): error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)'
1> c:\program files (x86)\microsoft visual studio 14.0\vc\include\type_traits(1469): note: With the following template arguments:
1> c:\program files (x86)\microsoft visual studio 14.0\vc\include\type_traits(1469): note: '_Callable=double (__thiscall MyClass::* )(double,double,double) const'
1> c:\program files (x86)\microsoft visual studio 14.0\vc\include\type_traits(1469): note: '_Types={std::reference_wrapper<MyClass>, double, double, double}'
1>c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(31): error C2440: 'initializing': cannot convert from 'std::_Binder<std::_Unforced,FUNC &,std::reference_wrapper<MyClass> &,double &,double &,double &>' to 'std::function<unknown-type (void)>'
1> with
1> [
1> FUNC=double (__thiscall MyClass::* )(double,double,double) const
1> ]
1> c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(31): note: No constructor could take the source type, or constructor overload resolution was ambiguous
1>c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(32): error C2664: 'void std::queue<std::function<double (void)>,std::deque<_Ty,std::allocator<_Ty>>>::push(const std::function<double (void)> &)': cannot convert argument 1 from 'std::function<unknown-type (void)>' to 'std::function<double (void)> &&'
1> with
1> [
1> _Ty=std::function<double (void)>
1> ]
1> c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(32): note: Reason: cannot convert from 'std::function<unknown-type (void)>' to 'std::function<double (void)>'
1> c:\users\siu.chan\documents\visual studio 2015\projects\testfunctionqueue\testfunctionqueue\testfunctionqueue.cpp(32): note: No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
So, I think this is an issue with vc++. Passing a member function works just fine when the next parameter is a pointer, but fails when it is a reference.
template <class F, class... A>
std::result_of_t<F(A...)> Foo::bar(F f, A... a)
{
return 0;
}
Foo f;
f.bar(&Foo::other_function, std::ref(f)); //error
f.bar(&Foo::other_function, &f); //success
Additionally, result_of in vc++ fails when the function type is a function (like void()), but clang and gcc both succeed.
template <class F, class... A>
struct Foo
{
typedef std::result_of_t<F(A...)> type;
};
Foo<int(int), int> //fails in only vc++

access to different data via c++ templates

I'm trying to make a manager, which provides access via templates to containers that store different types of data.
First of all, i made base manager class for storing different type of data
template <typename T>
class BaseMapManager{
public:
T add(T element, std::string name);
T remove(T element);
T remove(std::string name);
T remove(unsigned int id);
T get(std::string name);
T get(unsigned int id);
BaseMapManager() { id = 0; };
~BaseMapManager() { nameMap.clear(); idMap.clear(); };
protected:
std::map<std::string, T> nameMap;
std::map<unsigned int, T> idMap;
//each element of type T gets new unique id
unsigned int id;
//hide it
BaseMapManager(const BaseMapManager&) {};
BaseMapManager& operator=(const BaseMapManager&) {};
};
Then i made my concrete manager, which had to store 3 types of baseMapManagers:
class ResourceManager{
public:
//creates singleton
static ResourceManager* init(){
static ResourceManager singleton;
return &singleton;
}
template <typename T>
void load_resource(std::string path, std::string name){
get_map<std::shared_ptr<T>>().add(std::shared_ptr<T>(new T(path, name), name);
}
template <typename T>
std::shared_ptr<T> get_resource(std::string name){
get_map<T>().get(name);
}
template <typename T>
std::shared_ptr<T> get_resource(unsigned int id){
get_map<T>().get(id);
}
private:
BaseMapManager<std::shared_ptr<AnimationResource> > animationMap;
BaseMapManager<std::shared_ptr<ImageResource> > imageMap;
BaseMapManager<std::shared_ptr<FontResource> > fontMap;
template <typename T>
BaseMapManager<T>& get_map(){
if (std::is_same<T, std::shared_ptr<AnimationResource> >() == true) return animationMap;
if (std::is_same<T, std::shared_ptr<ImageResource> >() == true) return imageMap;
if (std::is_same<T, std::shared_ptr<FontResource> >() == true) return fontMap;
};
};
and now i got this:
1>------ Build started: Project: BOSS, Configuration: Debug Win32 ------
1> main.cpp
1>d:\programming\github projects\boss\boss\new\resourcemanager\resourcemanager.h(43):
error C2440: 'return' : cannot convert from 'BaseMapManager<T>' to 'BaseMapManager<T> &'
1> with
1> [
1> T=std::shared_ptr<ImageResource>
1> ]
1> and
1> [
1> T=std::shared_ptr<AnimationResource>
1> ]
1> d:\programming\github projects\boss\boss\new\resourcemanager\resourcemanager.h(21) : see reference to function template instantiation 'BaseMapManager<T> &ResourceManager::get_map<std::shared_ptr<_Ty>>(void)' being compiled
1> with
1> [
1> T=std::shared_ptr<AnimationResource>,
1> _Ty=AnimationResource
1> ]
1> d:\programming\github projects\boss\boss\new\main.cpp(17) : see reference to function template instantiation 'void ResourceManager::load_resource<AnimationResource>(std::string,std::string)' being compiled
1>d:\programming\github projects\boss\boss\new\resourcemanager\resourcemanager.h(44): error C2440: 'return' : cannot convert from 'BaseMapManager<T>' to 'BaseMapManager<T> &'
1> with
1> [
1> T=std::shared_ptr<FontResource>
1> ]
1> and
1> [
1> T=std::shared_ptr<AnimationResource>
1> ]
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
The goal is - providing access to different types on data using template functions like
manager->get_resource<AnimationResource>(itsName) //get it or
manager->load_resource<FontResource>(itsPath, itsName) //add it
Is there a better way to handle this maybe? Thanks!
edit
The source of your problem seams to be the is_same function not resolving correctly at compile time.
/edit
You can always have template functions that only work with the specified types.
For example:
template<>
BaseMapManager<AnimationResource> get_map<AnimationResource>()
{
return animationMap;
}
template<>
BaseMapManager<ImageResource> get_map<ImageResource>()
{
return imageMap;
}
template<>
BaseMapManager<FontResource> get_map<FontResource>()
{
return fontMap;
}

Using boost::multi_index_container

I've been attempting to use boost::multi_index_container to solve a problem I'm having. However, the multi_index_container fails to compile even the declaration. The error is deep in an MPL function and I have little idea where the fault lies.
boost::multi_index_container<
NodeType,
boost::multi_index::indexed_by<
boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>, decltype(node_comparator)>,
boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>
>
> open_set(
boost::make_tuple(node_comparator)
);
In this case, node_comparator is a lambda, and NodeType itself already has a std::hash specialization. Here's the text of the error:
1>d:\backups\code\boost_1_47_0\boost\multi_index\detail\node_type.hpp(56): error C2903: 'node_class' : symbol is neither a class template nor a function template
1> d:\backups\code\boost_1_47_0\boost\mpl\aux_\preprocessed\plain\apply_wrap.hpp(49) : see reference to class template instantiation 'boost::multi_index::detail::index_node_applier::apply<IndexSpecifierIterator,Super>' being compiled
1> with
1> [
1> IndexSpecifierIterator=boost::mpl::v_iter<boost::mpl::vector2<boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>,Wide::Sim::`anonymous-namespace'::<lambda8>>,boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>>,0>,
1> Super=boost::multi_index::detail::hashed_index_node<boost::multi_index::detail::index_node_base<NodeType,std::allocator<NodeType>>>
1> ]
1> d:\backups\code\boost_1_47_0\boost\mpl\aux_\preprocessed\plain\bind.hpp(207) : see reference to class template instantiation 'boost::mpl::apply_wrap2<F,T1,T2>' being compiled
1> with
1> [
1> F=boost::multi_index::detail::index_node_applier,
1> T1=boost::mpl::v_iter<boost::mpl::vector2<boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>,Wide::Sim::`anonymous-namespace'::<lambda8>>,boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>>,0>,
1> T2=boost::multi_index::detail::hashed_index_node<boost::multi_index::detail::index_node_base<NodeType,std::allocator<NodeType>>>
1> ]
1> d:\backups\code\boost_1_47_0\boost\mpl\aux_\preprocessed\plain\apply_wrap.hpp(49) : see reference to class template instantiation 'boost::mpl::bind2<F,T1,T2>::apply<U1,U2>' being compiled
1> with
1> [
1> F=boost::multi_index::detail::index_node_applier,
1> T1=boost::mpl::_2,
1> T2=boost::mpl::_1,
1> U1=boost::multi_index::detail::hashed_index_node<boost::multi_index::detail::index_node_base<NodeType,std::allocator<NodeType>>>,
1> U2=boost::mpl::v_iter<boost::mpl::vector2<boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>,Wide::Sim::`anonymous-namespace'::<lambda8>>,boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>>,0>
1> ]
1> d:\backups\code\boost_1_47_0\boost\mpl\aux_\preprocessed\plain\apply.hpp(63) : see reference to class template instantiation 'boost::mpl::apply_wrap2<F,T1,T2>' being compiled
1> with
1> [
1> F=boost::mpl::bind2<boost::multi_index::detail::index_node_applier,boost::mpl::_2,boost::mpl::_1>,
1> T1=boost::multi_index::detail::hashed_index_node<boost::multi_index::detail::index_node_base<NodeType,std::allocator<NodeType>>>,
1> T2=boost::mpl::v_iter<boost::mpl::vector2<boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>,Wide::Sim::`anonymous-namespace'::<lambda8>>,boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>>,0>
1> ]
1> d:\backups\code\boost_1_47_0\boost\mpl\aux_\preprocessed\plain\reverse_iter_fold_impl.hpp(82) : see reference to class template instantiation 'boost::mpl::apply2<F,T1,T2>' being compiled
1> with
1> [
1> F=boost::mpl::bind2<boost::multi_index::detail::index_node_applier,boost::mpl::_2,boost::mpl::_1>,
1> T1=boost::multi_index::detail::hashed_index_node<boost::multi_index::detail::index_node_base<NodeType,std::allocator<NodeType>>>,
1> T2=boost::mpl::v_iter<boost::mpl::vector2<boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>,Wide::Sim::`anonymous-namespace'::<lambda8>>,boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>>,0>
1> ]
1> d:\backups\code\boost_1_47_0\boost\mpl\reverse_iter_fold.hpp(43) : see reference to class template instantiation 'boost::mpl::aux::reverse_iter_fold_impl<N,First,Last,State,BackwardOp,ForwardOp>' being compiled
1> with
1> [
1> N=2,
1> First=boost::mpl::v_iter<boost::mpl::vector2<boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>,Wide::Sim::`anonymous-namespace'::<lambda8>>,boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>>,0>,
1> Last=boost::mpl::v_iter<boost::mpl::vector2<boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>,Wide::Sim::`anonymous-namespace'::<lambda8>>,boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>>,2>,
1> State=boost::multi_index::detail::index_node_base<NodeType,std::allocator<NodeType>>,
1> BackwardOp=boost::mpl::bind2<boost::multi_index::detail::index_node_applier,boost::mpl::_2,boost::mpl::_1>,
1> ForwardOp=boost::mpl::protect<boost::mpl::arg<1>>
1> ]
1> d:\backups\code\boost_1_47_0\boost\multi_index\detail\node_type.hpp(70) : see reference to class template instantiation 'boost::mpl::reverse_iter_fold<Sequence,State,BackwardOp>' being compiled
1> with
1> [
1> Sequence=boost::multi_index::indexed_by<boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>,Wide::Sim::`anonymous-namespace'::<lambda8>>,boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>>,
1> State=boost::multi_index::detail::index_node_base<NodeType,std::allocator<NodeType>>,
1> BackwardOp=boost::mpl::bind2<boost::multi_index::detail::index_node_applier,boost::mpl::_2,boost::mpl::_1>
1> ]
1> d:\backups\code\boost_1_47_0\boost\multi_index_container.hpp(75) : see reference to class template instantiation 'boost::multi_index::detail::multi_index_node_type<Value,IndexSpecifierList,Allocator>' being compiled
1> with
1> [
1> Value=NodeType,
1> IndexSpecifierList=boost::multi_index::indexed_by<boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>,Wide::Sim::`anonymous-namespace'::<lambda8>>,boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>>,
1> Allocator=std::allocator<NodeType>
1> ]
1> c:\repo\render\render\sim\simcontext.cpp(264) : see reference to class template instantiation 'boost::multi_index::multi_index_container<Value,IndexSpecifierList>' being compiled
1> with
1> [
1> Value=NodeType,
1> IndexSpecifierList=boost::multi_index::indexed_by<boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>,Wide::Sim::`anonymous-namespace'::<lambda8>>,boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>>
1> ]
Any suggestions as to the cause?
Edit: There's pretty much no context to be had. But here's an SSCCE for those of you who can't live without one:
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
struct NodeType {
int x, y, z;
float g_score;
NodeType(int ax, int ay, int az) {
x = ax;
y = ay;
z = az;
}
NodeType() {}
bool operator==(const NodeType& other) const {
return x == other.x && y == other.y && z == other.z;
}
};
template<> struct std::hash<NodeType> : public std::unary_function<const NodeType&, std::size_t> {
std::size_t operator()(const NodeType& node) const {
return std::hash<int>()(node.x * 100000 + node.y * 1000 + node.z);
}
};
template<> struct boost::hash<NodeType> : public std::unary_function<const NodeType&, std::size_t> {
std::size_t operator()(const NodeType& node) const {
return std::hash<int>()(node.x * 100000 + node.y * 1000 + node.z);
}
};
int main() {
auto h = [&](NodeType x) {
return 5.0f; // details irrelevant
};
auto node_comparator = [&](NodeType lhs, NodeType rhs) {
return lhs.g_score + h(lhs) < rhs.g_score + h(rhs);
};
boost::multi_index_container<
NodeType,
boost::multi_index::indexed_by<
boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>, decltype(node_comparator)>,
boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>
>
> open_set(
boost::make_tuple(node_comparator)
);
}
After your SSCCE post: maybe you forgot to add the following?
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/identity.hpp>
Other than that, I can't compile your code here because my environment is pre-C++11, but I did manage to make it work adding the missing includes and replacing lambdas with regular named functions. Note I had to change the construction args of open_setas explained in another answer:
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/identity.hpp>
struct NodeType {
int x, y, z;
float g_score;
NodeType(int ax, int ay, int az) {
x = ax;
y = ay;
z = az;
}
NodeType() {}
bool operator==(const NodeType& other) const {
return x == other.x && y == other.y && z == other.z;
}
};
template<> struct boost::hash<NodeType> : public std::unary_function<const NodeType&, std::size_t> {
std::size_t operator()(const NodeType& node) const {
return boost::hash<int>()(node.x * 100000 + node.y * 1000 + node.z);
}
};
double h(NodeType x) {
return 5.0f;
}
bool node_comparator(NodeType lhs, NodeType rhs) {
return lhs.g_score + h(lhs) < rhs.g_score + h(rhs);
}
int main() {
typedef boost::multi_index_container<
NodeType,
boost::multi_index::indexed_by<
boost::multi_index::ordered_non_unique<boost::multi_index::identity<NodeType>, bool (*)(NodeType,NodeType)>,
boost::multi_index::hashed_unique<boost::multi_index::identity<NodeType>>
>
> open_set_t;
open_set_t open_set(
boost::make_tuple(
boost::make_tuple(
boost::multi_index::identity<NodeType>(),
&node_comparator
),
open_set_t::nth_index<1>::type::ctor_args()
)
);
}
Additional note: your lambda functions are taking NodeTypes by value, I guess they'd be more efficient if they accepted their arguments as const NodeType&s.
Trying to guess what the problem is with so little context makes for a fun pastime but reduces your chances that you get a useful answer. Ideally you should be providing a complete testcase (i.e. a short compilable program) showing the issue. Anyway, a shot in the dark: you say that NodeTypehas a dedicated std::hash specialization, but Boost.MultiIndex uses boost::hash as its default hash generator. Try looking there.
Another shot in the dark (i think this is it): as decltype(node_comparator) is not default constructible you have to provide an initialization value (node_comparator itself) during open_setconstruction. This is what seemingly you're trying to do, but incorrectly: the right way is as follows (modulo potential typos, more details here):
typedef boost::multi_index_container<
NodeType,
...
> open_set_t;
open_set_t open_set(
boost::make_tuple(
boost::make_tuple(
boost::multi_index::identity<NodeType>(),
node_comparator
),
open_set_t::nth_index<1>::type::ctor_args()
)
);
Given the verbosity imposed by the use of a lambda expression here, I think you're better off by writing a used-defined, default constructible comparator class instead of node_comparator.