You are not logged in.

#1 2009-10-13 03:52:10

caelestis
Member
Registered: 2009-04-04
Posts: 88

g++ problem

The following code works fine with VC express, but not in GCC. Does anyone know why it won't compile? It gives this error:

conversion from 'main()::functor' to non-scalar type 'std::tr1::function<void()>' requested

Same thing happens if I use boost::function instead of std::tr1::function.

#include <iostream>
#include <tr1/functional>
#include <tr1/functional_hash.h>

void callfunc(std::tr1::function<void()> func) {func();}

int main() {
    struct functor {
        void operator()(void) {std::cout << "lol" << std::endl;}
    };
    functor f;
    callfunc(f);
}

Offline

#2 2009-10-13 03:56:34

sr
Member
Registered: 2009-10-12
Posts: 51

Re: g++ problem

I don't know the internals of tr1::function, but it seems to me that g++ is complaining about a valid failed type conversion.

Could you try declaring functor as:

struct functor: public std::tr1::function<void()> {

Offline

#3 2009-10-13 04:11:53

caelestis
Member
Registered: 2009-04-04
Posts: 88

Re: g++ problem

You suggested:

#include <iostream>
#include <tr1/functional>
#include <tr1/functional_hash.h>

using std::tr1::function;

void callfunc(function<void()> func) {func();}

int main() {
    struct functor : public function<void()>  {
        void operator()(void) {std::cout << "lol" << std::endl;}
    };
    functor f;
    callfunc(f);
}

This happens:

terminate called after throwing an instance of 'std::tr1::bad_function_call'  what(): std::exception

Offline

#4 2009-10-13 04:27:22

sr
Member
Registered: 2009-10-12
Posts: 51

Re: g++ problem

Ah, well smile it was just the simplest way of avoiding that particular error, short of an explicit cast, which I assumed wouldn't work either.

Edit: could you try moving the struct declaration out of main, instead? I believe gcc's local class declarations are causing the problem here, since according to tr1, your syntax appears perfectly correct.

Last edited by sr (2009-10-13 04:47:17)

Offline

#5 2009-10-13 04:53:07

sr
Member
Registered: 2009-10-12
Posts: 51

Re: g++ problem

Just to be clear, this works for me:

#include <iostream>
#include <tr1/functional>

void callfunc(std::tr1::function<void()> &func) {func();}

struct functor{
    void operator()() {std::cout << "lol" << std::endl;}
};

int main(int, char*[]) {

    std::tr1::function<void()> f = functor();
    callfunc(f);
}

Moving the struct into main() doesn't, for some reason - at least, I *think* I understand why it doesn't, but don't see why it works that way.

Offline

#6 2009-10-13 20:21:55

caelestis
Member
Registered: 2009-04-04
Posts: 88

Re: g++ problem

Nvm, gcc doesn't support it yet.

http://gcc.gnu.org/gcc-4.4/cxx0x_status.html

Offline

Board footer

Powered by FluxBB