If using std::map<std::string,object> to keep objects ordered by name, the map's value_type (std::pair<string,object>) is a convenient class which warrants useful functionality, e.g.
typedef std::map<std::string,object> object_map;
typedef typename object_map::value_type named_object;
void function(named_object const&);
// with the following possible use case
void foo(std::string const&name, object_map const &omap)
{
auto obj=omap.find(name);
if(obj==omap.end()) throw std::runtime_error("name not found");
function(*obj);
}
So far, so good. I later extend my objects
struct extended_object : object { /* more data */ };
and keep the extended objects ordered by name, too, via std::map<std::string,extended>.
I may define.
typedef std::map<std::string,extended_object> extended_object_map;
typedef typename extended_object_map::value_type named_extended_object;
Unfortunately, I cannot
void foo(std::string const&name, extended_object_map const& emap)
{
auto eobj=emap.find(name);
if(eobj==emap.end()) throw std::runtime_error("name not found");
function(*eobj); // cannot convert *eobj to const named_object&
}
Now, my question is how to solve this problem? I considered using a reinterpret_cast<>
function(reinterpret_cast<const named_object&>(*eobj));
which essentially assumes that the data layouts of named_object and named_extended_object are exactly like that of base and derived. Is this safe/recommendable?
Alternatively, I considered to use std::set (instead of std::map) with key types
named_object and re-define
struct named_extended_object : named_object { /* more data */ };
The problem with this approach is that in order to std::set::find() an object, I must provide not just a name string, but a whole object or even extended object. According to cppreference, std::set::find() will have a resolution to this problem in C++14 (overloads 3&4), but what shall I do in the mean time?
Change your function to
void function(const std::string& name, const object& obj);
Then call it like
auto obj = omap.find(name);
function(obj->first, obj->second);
// or
auto eobj = emap.find(name);
function(eobj->first, eobj->second);
the map's value_type (std::pair<string,object>) is a convenient class which warrants useful functionality
N.B. that is not the map's value_type. It's std::pair<const string,object>
The reinterpret_cast results in undefined behaviour when a named_extended_object is accessed through the reference, it violates what some compilers call "strict aliasing" rules, and can cause your program to misbehave if the compiler optimises using type-based alias analysis. Do not use reinterpret_cast like that. In handwavy Liskov Substitution Principle terms, extended_object IS-A object, so it's OK to substitute an extended_object where an object is expected, but pair<T, extended_object> IS-NOT-A pair<T, object> so cannot be used interchangeably.
I like D Drmmr's answer, but if you don't want to do that, another option is a template:
template<typename Obj>
void function(const std::pair<const std::string, Obj>&)
{
// ...
}
This will accept pair<const string, object> and also pair<const string, extended_object> arguments. If the body of the template only tries to access the members that are present in object then it will work perfectly for both argument types.
If you don't want to expose that template to users of the function, then declare two overloads:
void function(const named_object&);
void function(const named_extended_object&);
Then in the implementation file:
namespace {
template<typename Obj>
void function_impl(const std::pair<const std::string, Obj>&)
{
// common implementation ...
}
}
void function(const named_object& no) { function_impl(no); }
void function(const named_extended_object& neo) { function_impl(neo); }
Related
If I want to use std::any I can use it with RTTI switched off. The following example compiles and runs as expected also with -fno-rtti with gcc.
int main()
{
std::any x;
x=9.9;
std::cout << std::any_cast<double>(x) << std::endl;
}
But how std::any stores the type information? As I see, if I call std::any_cast with the "wrong" type I got std::bad_any_cast exception as expected.
How is that realized or is this maybe only a gcc feature?
I found that boost::any did also not need RTTI, but I found also not how that is solved. Does boost::any need RTTI?.
Digging into the STL header itself gives me no answer. That code is nearly unreadable to me.
TL;DR; std::any holds a pointer to a static member function of a templated class. This function can perform many operations and is specific to a given type since the actual instance of the function depends on the template arguments of the class.
The implementation of std::any in libstdc++ is not that complex, you can have a look at it:
https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/any
Basically, std::any holds two things:
A pointer to a (dynamically) allocated storage;
A pointer to a "storage manager function":
void (*_M_manager)(_Op, const any*, _Arg*);
When you construct or assign a new std::any with an object of type T, _M_manager points to a function specific to the type T (which is actually a static member function of class specific to T):
template <typename _ValueType,
typename _Tp = _Decay<_ValueType>,
typename _Mgr = _Manager<_Tp>, // <-- Class specific to T.
__any_constructible_t<_Tp, _ValueType&&> = true,
enable_if_t<!__is_in_place_type<_Tp>::value, bool> = true>
any(_ValueType&& __value)
: _M_manager(&_Mgr::_S_manage) { /* ... */ }
Since this function is specific to a given type, you don't need RTTI to perform the operations required by std::any.
Furthermore, it is easy to check that you are casting to the right type within std::any_cast. Here is the core of the gcc implementation of std::any_cast:
template<typename _Tp>
void* __any_caster(const any* __any) {
if constexpr (is_copy_constructible_v<decay_t<_Tp>>) {
if (__any->_M_manager == &any::_Manager<decay_t<_Tp>>::_S_manage) {
any::_Arg __arg;
__any->_M_manager(any::_Op_access, __any, &__arg);
return __arg._M_obj;
}
}
return nullptr;
}
You can see that it is simply an equality check between the stored function inside the object you are trying to cast (_any->_M_manager) and the manager function of the type you want to cast to (&any::_Manager<decay_t<_Tp>>::_S_manage).
The class _Manager<_Tp> is actually an alias to either _Manager_internal<_Tp> or _Manager_external<_Tp> depending on _Tp.
This class is also used for allocation / construction of object for the std::any class.
Manual implementation of a limited RTTI is not that hard. You're gonna need static generic functions. That much I can say without providing a complete implementation.
here is one possibility:
class meta{
static auto id(){
static std::atomic<std::size_t> nextid{};
return ++nextid;//globally unique
};
std::size_t mid=0;//per instance type id
public:
template<typename T>
meta(T&&){
static const std::size_t tid{id()};//classwide unique
mid=tid;
};
meta(meta const&)=default;
meta(meta&&)=default;
meta():mid{}{};
template<typename T>
auto is_a(T&& obj){return mid==meta{obj}.mid;};
};
This is my first observation; far from ideal, missing many details. One may use one instance of meta as a none-static data member of his supposed implementation of std::any.
One of possible solutions is generating unique id for every type possibly stored in any (I assume You know moreless how any internally works). The code that can do it may look something like this:
struct id_gen{
static int &i(){
static int i = 0;
return i;
}
template<class T>
struct gen{
static int id() {
static int id = i()++;
return id;
}
};
};
With this implemented You can use the id of the type instead of RTTI typeinfo to quickly check the type.
Notice the usage of static variables inside functions and static functions. This is done to avoid the problem of undefined order of static variable initialization.
I need a std:map data structure that is read only, which means I have to fill it once with data and then only read those values, never change them or add additional ones.
My non-const version looks like this:
//in .h
#include <string>
#include <map>
std::map<std::string, int> myMap;
void initMap();
//in .cpp
#include "foo.h"
void initMap() {
myMap["Keys"] = 42;
}
Then I'd call initMap() once in my code and be done.
Now I've read several questions here already and it seems non-trivial to achieve const-ness for the map.
Making it a std::map<std::string, const int> won't allow me to fill it in the initMap().
Filling it with a non-const temp and the copy constructor on definition doesn't work either, as the copy constructor doesn't easily take the non-const version as input.
Making it a const std::map<std::string, int> (which I could fill with a non-const copy during definition) would disable the use of the [] operator for value access.
So is there a way to achieve (value) const-ness and initialize the structure (preferably in the header file)?
BTW: Neither C++0x nor C++11 nor boost:: is an option.
Couldn't you use the insert() method available for std::map?
http://www.cplusplus.com/reference/map/map/insert/
Edit : (solution) myMap.insert(std::pair<std::string, const int>("Keys", 42));
As far as I understand it, the reason why this works is because the constructor for the pair, pair (const first_type& a, const second_type& b), initializes its members first and second using the constructors for first_type and second_type, taking a and b as their respective parameter.
With the solution you were trying to use, my comprehension is that myMap["Keys"] = 42; initializes the member second of the map (of type const int) using the default constructor for int. Then a value is attempted to be assigned to that member. As this is done outside the constructor of the class map, the const declaration makes this impossible.
With the solution using insert(), the members are initialized in the constructor of the pair. Thus they can be declared const. The same operation is done when the pair is copied to the map.
While this is not possible for you, others who wants to do this and that have a C++11 compatible compiler, could use uniform initialization:
std::map<std::string, const int> myMap = {
{ "keys", 42 }
};
Oh and by the way, don't define the map in the header file. Instead declare it as extern in the header file, then define it in the source file.
The simplest solution is to write your own, wrapping the
standard map class:
template <typename KeyType, typename MappedType, typename CmpType>
class ConstantMap
{
typedef std::map<KeyType, MappedType, CmpType> Impl;
Impl myImpl;
public:
typedef Impl::value_type value_type;
template <ForwardIterator>
ConstantMap( ForwardIterator begin, ForwardIterator end, CmpType cmp = CmpType() )
: myImpl( begin, end, cmp )
{
}
// necessary if [] is not going to work for missing keys
bool contains( KeyType const& key ) const
{
return myImpl.find( key ) != myImpl.end();
}
MappedType const& operator[]( KeyType const& key ) const
{
Impl::const_iterator elem = myImpl.find( key );
if ( elem == myImpl.end() ) {
// Not found, do what you want (maybe throw an exception)
}
return elem.second;
}
};
You can initialze the map by passing it iterators to a sequence
of anything which can convert to value_type.
Depending on your needs, you may want to add additional
forwarding typedefs, functions, etc. If you're using C++11, you
may also want to create a constructor which can use a list
initializer.
If the map can't mutate, you should use const map<string, int>, and not map<string, const int>: the second version allows insertion and deletion of objects.
Sadly, you are going to have to lose the [] operator; C++ doesn't have an ImmutableMap, or something like that. However, std::map::at and std::map::find aren't too bad...
Something much simpler which has a smaller footprint and is faster:
static const int MyMapData[] = {
42 // index 0 is mapped to "key"
};
struct MyMap
{
const int& operator[](std::string key) const
{
switch (key) {
case "Keys": return MyMapData[0];
default: return NotANumber; // Return 0 and raise an assertion, or return "Not a Number".
}
}
};
Easy to maintain, no use of templates, no use of boost libraries and compilable everywhere.
I have a set like this: set<weak_ptr<Node>, owner_less<weak_ptr<Node> > > setName;
It works fine. But I would like to change it to an unordered set. However, I get about six pages of errors when I do that. Any ideas how to do that?
After looking through all the pages of error messages I found to lines that might help.
/usr/include/c++/4.7/bits/functional_hash.h:60:7: error: static assertion failed: std::hash is not specialized for this type
/usr/include/c++/4.7/bits/stl_function.h: In instantiation of ‘bool std::equal_to<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = std::weak_ptr<Node>]’:
The short and unfortunate answer is that while shared_ptr<> can be used safely as a key in an unordered set or map, weak_ptr<> cannot and must not. No amount of trickery can make it safe.
This is because weak_ptr's interface does not expose access to the shared control object, which is the basis of comparing by owner_before() when used in an ordered set or map.
While it may seem reasonable to lock the pointer and then hash the shared_ptr, it is not. If the last shared_ptr goes out of scope the hash value will change, which will result in undefined behaviour next time your set or map is iterated. This will most likely go un-noticed until your code is in production in front of customers where you get unexpected and inexplicable loss of functionality occasionally, but your unit tests will still pass flawlessly, giving you the false idea that your test coverage is good, your code is reliable and it is the users, hardware or network that's to blame.
So, in summary, if you're going to use weak_ptr's to build your non-owning object caches (for which they are excellent) you need use a std::set<weak_ptr> and suffer the miniscule performance hit (although in reality this will be dwarfed by the performance loss caused by the mutex that protects the set).
If you really want to use a weak_ptr as an unordered key you will have to write your own (hint: use the address of the shared control block as the basis for the hash function).
I don't think that suggested hash function is correct. If all shared pointers to the object disappears then weak_ptr<X>::lock() will return empty shared_ptr, whose hash value is probably zero. So the hash function can return different values throughout time.
I think that the correct solution here is to use
boost::unordered_map<X*, boost::weak_ptr<X>>. Type X* can be easily use as a key to hash map and weak_ptr<X> as the value gives you chance to find out whether referenced object still exists.
To store value to this hash, you can use something like:
if (boost::shared_ptr<X> p = wp.lock()) {
// weak_ptr is still valid
ptrs.insert(std::make_pair(p.get(), p));
}
Please read Richard Hodges answer below as mine is incorrect, despite being the accepted solution.
Since unordered_sets are hash-based you have to provide a hash function object for the std::weak_ptr data-type.
If you take a look at the unordered_set template-parameters
template<class Key,
class Hash = std::hash<Key>,
class Pred = std::equal_to<Key>,
class Alloc = std::allocator<Key> >
class unordered_set;
you'll notice that std::unordered_set provides you with a default std::hash<> template parameter. But since std::hash does only provide specializations for a specific set of data types, you might have to provide your own.
The error-message you quoted tells you, that no std::hash<> specialization for std::weak_ptr<> exists, so you have to provide your own hashing function for that:
template<typename T>
struct MyWeakPtrHash : public std::unary_function<std::weak_ptr<T>, size_t> {
size_t operator()(const std::weak_ptr<T>& wp)
{
// Example hash. Beware: As zneak remarked in the comments* to this post,
// it is very possible that this may lead to undefined behaviour
// since the hash of a key is assumed to be constant, but will change
// when the weak_ptr expires
auto sp = wp.lock();
return std::hash<decltype(sp)>()(sp);
}
};
Edit:
You also need to provide an equality function, since no std::equal_to for weak_ptr is provided.
Taking a possible way to do this from "Equality-compare std::weak_ptr" on Stackoverflow:
template<typename T>
struct MyWeakPtrEqual : public std::unary_function<std::weak_ptr<T>, bool> {
bool operator()(const std::weak_ptr<T>& left, const std::weak_ptr<T>& right)
{
return !left.owner_before(right) && !right.owner_before(left);
}
};
All combined this gives us the following:
std::unordered_set<std::weak_ptr<T>,
MyWeakPtrHash<T>,
MyWeakPtrEqual<T>> wpSet;
A working solution is given here: How to compute hash of std::weak_ptr? Below is a slightly expanded variant that adds missing details. Unlike the earlier answers given above, this works because the hash is computed and stored before the shared_ptr count drops to zero.
namespace foobar
{
// Public inheritance was used to avoid having to
// duplicate the rest of the API. Unfortunately this
// allows object slicing. So, an alternate solution is
// to use private inheritance, and `using` to provide
// the missing API.
template<class T>
struct hashable_weak_ptr : public std::weak_ptr<T>
{
hashable_weak_ptr(std::shared_ptr<T>const& sp) :
std::weak_ptr<T>(sp)
{
if (!sp) return;
_hash = std::hash<T*>{}(sp.get());
}
std::size_t get_hash() const noexcept { return _hash; }
// Define operator<() in order to construct operator==()
// It might be more efficient to store the unhashed
// pointer, and use that for equality compares...
friend bool operator<(hashable_weak_ptr const& lhs,
hashable_weak_ptr const& rhs)
{
return lhs.owner_before(rhs);
}
friend bool operator!=(hashable_weak_ptr const& lhs,
hashable_weak_ptr const& rhs)
{
return lhs<rhs or rhs<lhs;
}
friend bool operator==(hashable_weak_ptr const& lhs,
hashable_weak_ptr const& rhs)
{
return not (lhs != rhs);
}
private:
std::size_t _hash = 0;
};
} // namespace foobar
namespace std
{
// Specializations in std namespace needed
// for above to be usable.
template<class T>
struct owner_less<foobar::hashable_weak_ptr<T>>
{
bool operator()(const foobar::hashable_weak_ptr<T>& lhs,
const foobar::hashable_weak_ptr<T>& rhs) const noexcept
{
return lhs.owner_before(rhs);
}
};
template<class T>
struct hash<foobar::hashable_weak_ptr<T>>
{
std::size_t operator()(const foobar::hashable_weak_ptr<T>& w) const noexcept
{
return w.get_hash();
}
};
} // namespace std
A variant of this question was first asked here: Why was std::hash not defined for std::weak_ptr in C++0x? and the latest standards committee draft that resolves this is here: JTC1 WG21 P1901.
I'm using template functions for object construction to create objects from reflection data, and it works pretty well, but now I want to support STL container types in the reflection system so that objects such as:
// Note - test case only
// for real world usage it would probably not be structured like this
// and the phrases would be mapped by an id or something
struct Phrases {
std::vector<std::string> phrases;
};
typedef std::string Lang;
struct Langs {
std::map< Lang, Phrases > translations;
};
Can be supported. I can do some regex magic on the return of
typeid( object ).name()
to figure out if an object is a vector or a map, and what the parameter arguments for the object is. And I have tried some template magic to do it something like the following, where CreateString, ConstructString & DestroyString are stand in functions and the data is stand in as well for something a bit more complex that uses a type database to handle object construction.
// Representational of code, basically a copy-paste to a different test project where I can work out the problems with this specific vector problem
// Vector specialised construction
template <typename T> void ConstructVector( void* object, const std::vector<std::string>& data ) {
T* vec = (T*)object;
Name vector_type = GetVectorTypeName<T>();
void *obj;
CreateString(&obj);
// All fields in this type should be valid objects for this vector
for( std::vector<std::string>::const_iterator it = data.begin(), end = data.end(); it != end; ++it ) {
// Push it
vec->push_back(*obj);
// Get address to new instance
void *newly = &vec->back();
ConstructString(newly,*it);
}
DestroyString(&obj);
}
Which doesn't work owing to the illegal indirection with "vec->push_back(*obj);" which I can't case because I don't actually know the type. Basically what I need to be able to do is create this vector with some blank unset elements already in it, or add new elements to it without actually having the type, because if I can get a pointer to a memory block inside the vector I can roll with that and construct the object. But the vector add requirements such as
vector::push_back( T& value )
or
vector::insert( Iter&, T& )
Won't work for me unless I can get my hands on that T type from inside the template
pastebin of testing code to try and solve this:
http://pastebin.com/1ZAw1VXg
So my question is, how can I get the std::string part of a std::vector declaration when I'm inside a template like
template <typename T> void SomeFunc() {
// Need to get std::string here somehow
// Alternatively need to make the vector a certain size and then
// get pointers to it's members so I can construct them
}
SomeFunc<std::vector<std::string>>>();
There are two ways to accomplish this.
1) Either you make use of the fact that std::vector<> (like all standard library container classes) maintains a member type value_type, which represents the type of the elements stored in the vector. So you can do this:
template <typename T> void SomeFunc() {
typename T::value_type s; // <--- declares a `std::string` object
// if `T` is a `std::vector<std::string>`
}
2) Or else, you change the declaration of your function and make use of template template parameters:
template <template <typename> class T, typename Elem>
void SomeFunc(T<Elem> &arg)
{
Elem s;
}
However, there is a small problem with that: std::vector is really a template with two parameters (element type and allocator type), which makes it a little difficult to use the template template parameters and still keep the syntax simple. One thing that worked for me is to declare an alias of the vector type that leaves only one template parameter:
template <typename Elem>
using myvector = std::vector<Elem>;
Then I can use SomeFunc like this:
int main()
{
myvec<std::string> vec;
SomeFunc(vec);
}
In c++11, you can use decltype and std::decay to that effect:
std::vector<int> vec;
using T = typename std::decay<decltype(*vec.begin())>::type;
I'm new to std::generate and have attempted to structure a program which uses it to initialize vectors. However it's behaving differently to my expectations.
I have an abstract base class:
template <typename G>
class RandomAllele {
public:
RandomAllele() { /* empty */ }
virtual ~RandomAllele() { /* empty */ }
virtual G operator()() const = 0;
};
Which is extended by (for example):
class RandomInt : public RandomAllele<int> {
public:
RandomInt(int max) : max_(max) {}
int operator()() const { return rand() % max_; }
private:
int max_;
};
I pass an instance of my inheriting class to a factory class by pointer, and then use it as the third argument for std::generate:
template<typename G, typename F>
class IndividualFactory {
public:
IndividualFactory(int length, const RandomAllele<G> *random_allele)
: length_(length), random_allele_(random_allele) { /* empty */ }
individual_type *generate_random() const {
std::vector<G> *chromosome = new std::vector<G>(length_);
std::generate(chromosome->begin(), chromosome->end(), *random_allele_); */
return new individual_type(chromosome);
}
private:
int length_;
RandomAllele<G> *random_allele_;
};
Now I get an error saying that RandomAllele cannot be instantiated because it's an abstract class. Why does generate need to instantiate it when the pointer already exists? And why is it trying to use the base class instead of the inheriting class RandomInt?
This works fine if I replace std::generate with:
for(auto iter = chromosome->begin(); iter != chromosome->end(); ++iter)
*iter = (*random_allele_)();
But I still wish to understand why it behaves strangely, and I'd prefer to use generate if there is a way to do this.
Thanks for your time,
Rhys
As others have mentioned above, the generate and generate_n functions take their generator objects by value, precluding you from directly using inheritance in this context.
However, one trick you can do is to apply the Fundamental Theorem of Software Engineering:
Any problem can be solved by adding another layer of indirection
Rather than directly passing in a polymorphic functor, instead pass in a wrapper functor that stores a pointer to this polymorphic functor and then forwards the call appropriately. For example:
template <typename T> class IndirectFunctor {
public:
explicit IndirectFunctor(RandomAllele<T>* f) : functor(f) {
// Handled in initializer list
}
T operator() () const {
return (*functor)();
}
private:
RandomAllele<T>* functor;
};
If you then pass this object into generate, as seen here:
RandomAllele<T>* functor = /* ... create an allele ... */
std::generate(begin, end, IndirectFunctor<T>(functor));
Then everything will work as intended. The reason for this is that if you copy IndirectFunctor<T> by value, then you just shallow-copy the stored pointer, which will still point to the RandomAllele you want to call. This avoids the slicing problem you were encountering because it never tries directly copying an object of type RandomAllele through a base class pointer. It always copies the wrapper object, which never tries to duplicate RandomAllele.
Hope this helps!
std::generate's generator is passed by value, and therefore copied.
In general the C++ standard library implements static polymorphism (templates) and doesn't support runtime polymorphism (virtual methods) for function objects. This is because it passes all its function objects by values, assuming them to be stateless or almost stateless such that the added indirection of passing by pointer or reference would be more expensive than by value.
Since it's passed by value this results in slicing and when you try to use a RandomAllele<G> it thinks you mean that exact class not whatever derived type it actually points to. Instead of templating on G just template on the exact generator functor type you desired directly.
The issue is that all standard algorithms take their arguments by value, to conform with traditional C constraints. So here the std::generate() algorithm take the functor by value. Your functor, of type RandomAllele<int>, is of abstract type. Yes, it's a pointer pointing at a concrete type, but the pointer is of an abstract type. In copying this object, the algorithm calls the copy constructor of RandomAllele<int>; i.e., the algorithm constructs an instance of abstract type. And this is something the C++ language forbids.
You can tell the runtime environment not to worry too much like so:
RandomInt *cp = dynamic_cast<RandomInt*>(random_allele);
if( ! cp ) {
// i thought the pointer is of RandomInt. It isn't. Err.
std::terminate(); // or something
}
std::generate(chromosome->begin(), chromosome->end(), *cp);
The prototype is:
template <class ForwardIterator, class Generator>
void generate ( ForwardIterator first, ForwardIterator last, Generator gen );
Hence gen is passed by value, so the compiler attempts to construct a RandomAllele by copy, hence problem.
The solution is to use an Envelope to provide the needed indirection:
template<class G>
class RandomAlleleEnvelope
{
public:
RandomAlleleEnvelope(const RandomAllele<G>* ra)
: ra_(ra)
{}
int operator()() const { return (*ra_)(); }
private:
const RandomAllele<G>* ra_;
};
std::generate<std::vector<int>::iterator,RandomAlleleEnvelope<int> >(chromosome->begin(), chromosome->end(), random_allele_);
Also note there is another solution, define your own generate to use a reference:
template <class ForwardIterator, class Generator>
void referenceGenerate ( ForwardIterator first, ForwardIterator last,
const Generator& gen )
{
while (first != last) *first++ = gen();
}
referenceGenerate(chromosome->begin(), chromosome->end(), *random_allele_);
I also think the following should work, that is to use the standard generate and explicitly make it handle a reference type:
std::generate<std::vector<int>::iterator, const RandomAllele<int>& >
(chromosome->begin(), chromosome->end(), *random_allele_);
I say should because this fails is instantiate on VS2010. On the other hand, if I can define my own:
template <class ForwardIterator, class Generator>
void myGenerate ( ForwardIterator first, ForwardIterator last, Generator gen )
{
while (first != last) *first++ = gen();
}
myGenerate<std::vector<int>::iterator, const RandomAllele<int>& >
(chromosome->begin(), chromosome->end(), *random_allele_);
The VS2010 fails because it implements std::generate is terms of another std::generate which defaults back to non-reference parameters.