|
Boost Users : |
Subject: Re: [Boost-users] Scoped Pairs of functions?
From: Nat Linden (nat_at_[hidden])
Date: 2011-08-19 13:58:41
On Fri, Aug 19, 2011 at 7:00 AM, Brian Allison
<brian.w.allison_at_[hidden]> wrote:
> Is there a way to generalize the return type so that ScopedResource could be in a library and the user could use it for pairing two functions that have int and void return types respectively?
? I don't think that's necessary. The following still works for me (g++):
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
void acquire_fixed()
{
std::cout << "Acquiring fixed resource\n";
}
int iacquire_fixed()
{
int ret(34);
std::cout << "Acquiring fixed resource, returning " << ret << '\n';
return ret;
}
void release_fixed()
{
std::cout << "Releasing fixed resource\n";
}
void acquire(const std::string& resource)
{
std::cout << "Acquiring " << resource << '\n';
}
int iacquire(const std::string& resource)
{
int ret(17);
std::cout << "Acquiring " << resource << ", returning " << ret << '\n';
return ret;
}
void release(const std::string& resource)
{
std::cout << "Releasing " << resource << '\n';
}
class ScopedResource
{
public:
typedef boost::function<void()> ResourceFunc;
ScopedResource(const ResourceFunc& acq, const ResourceFunc& rel):
mRelease(rel)
{
acq();
}
virtual ~ScopedResource()
{
mRelease();
}
private:
ResourceFunc mRelease;
};
int main(int argc, char *argv[])
{
{
ScopedResource fixed(acquire_fixed, release_fixed);
std::cout << "during acquire_fixed()\n";
}
{
ScopedResource fixed(iacquire_fixed, release_fixed);
std::cout << "during iacquire_fixed()\n";
}
{
ScopedResource something(boost::bind(acquire, "something"),
boost::bind(release, "something"));
std::cout << "during acquire('something')\n";
}
{
ScopedResource something(boost::bind(iacquire, "something"),
boost::bind(release, "something"));
std::cout << "during iacquire('something')\n";
}
return 0;
}
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net