简体   繁体   中英

Higher-order functions in C++, using std::wcout fails with error C2248

I'm playing around with implementing functional-style stuff in C++. At the moment, I'm looking at a continuation-passing style for enumerating files.

I've got some code that looks like this:

namespace directory
{
    void find_files(
        std::wstring &path,
        std::function<void (std::wstring)> process)
    {
        boost::filesystem::directory_iterator begin(path);
        boost::filesystem::directory_iterator end;

        std::for_each(begin, end, process);
    }
}

Then I'm calling it like this:

directory::find_files(source_root, display_file_details(std::wcout));

...where display_file_details is defined like this:

std::function<void (std::wstring)>
    display_file_details(std::wostream out)
{
    return [&out] (std::wstring path) { out << path << std::endl; };
}

The plan is to pass a continuation to find_files , but to be able to pass composed functions into it.

But I get the error:

error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' :
    cannot access private member declared in
    class 'std::basic_ios<_Elem,_Traits>'

What am I doing wrong? Am I insane for trying this?

Note: my functional terminology (higher-order, continuations, etc.) is probably wrong. Feel free to correct me.

In display_file_details , you need to take your wostream by reference. iostream copy constructors are private.

Upon looking more deeply into the compiler output, I found this:

This diagnostic occurred in the compiler generated function
    'std::basic_ostream<_Elem,_Traits>::
        basic_ostream(const std::basic_ostream<_Elem,_Traits> &)'

It turns out that basic_ostream doesn't have an available copy constructor.

Changing std::wostream out to std::wostream & out fixes it. At least to the point that I get a bunch of other errors. These were easily fixed by:

std::for_each(begin, end,
    [&process] (boost::filesystem::directory_entry d)
    { process(d.path().wstring()); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM