tags:

views:

78

answers:

2

hello.

Suppose I need to implement factory function which returns object O which inherits/has members inheriting from boost::noncopyable.

struct O : boost::noncopyable {};
O factory() { return O(); }

Obviously returning value fails to compile.

What method do you know or use to implement such factory methods? I really like to avoid overriding copy constructor if it is possible and to return value rather than reference or pointer.

after some tinkering and link from codeka I managed this (no idea how portable does this, seems to work with g++):

template<class E>
struct threads_parallel_for_generator
    : for_generator<E, threads_parallel_for_generator<E> > {

    typedef for_generator<E, threads_parallel_for_generator> base_type;

    struct factory_constructor {
        explicit factory_constructor(const E &expression)
            : expression_(expression) {}
        operator const E&() const { return expression_; }
    private:
        E expression_;
    };

    threads_parallel_for_generator(const factory_constructor & constructor)
        : base_type(constructor, *this) {}

private:
    boost::mutex mutex_;
};


template<class E>
static threads_parallel_for_generator<E>
parallel_for(const E &expression) {
    typedef threads_parallel_for_generator<E> generator;
    return typename generator::factory_constructor(expression);
}

Thanks

+6  A: 

If is noncopyable then you must return a pointer or reference. That is the point of noncopyable.

If it's your class that is noncopyable then you probably need to change the design as you obviously need to copy it. If you have members that are noncopyable that you can't change then perhaps your class could hold pointers to the noncopyable objects?

Gary
I know your point, but there are cases where instantiating non-copyable object directly is too difficult. I think your answer should be a comment rather.
aaa
design problem, maybe. however, I do not need to copy, I need to move object from factory function (essentially constructor to hide crazy template instantiation parameters in object). holding pointers really defeats the purpose of non-copyable in my case
aaa
Transfer ownership of a pointer - that's moving.
Gary
+2  A: 

Boost does have support for this in the form of BOOST_MOVABLE_BUT_NOT_COPYABLE, but in my opinion it's far more trouble than it's worth to implement (without C++0x) and just returning a (smart) pointer is far easier...

(Note: the above is not an "official" boost library...)

Dean Harding
troubles may be worth it for me, if it leads to cleaner syntax (I am working with some crazy template expressions married to boost::mutex)
aaa
@aaa: sure, I guess it just depends on the situation.
Dean Harding