2

请考虑以下代码:

template<class basic_ios_type>
class basic_ios_adaptor;

template<template<typename, class> class basic_ios_type, typename char_type, class traits_type>
class basic_ios_adaptor<basic_ios_type<char_type, traits_type>>
    : public basic_ios_type<char_type, traits_type>
{
public:
    typedef basic_ios_type<char_type, traits_type> base_type;

    basic_ios_adaptor(base_type const& other)
        : base_type(other)
    {
    }
};

唯一可用的构造函数是复制构造函数,它接受对基类型的 const 引用。示例用法:

std::ofstream                    x(std::ofstream(""));  // ok
basic_ios_adaptor<std::ofstream> y(std::ofstream(""));  // error

视觉 C++:

'std::basic_ios<_Elem,_Traits>::basic_ios' : 无法访问在类 'std::basic_ios<_Elem,_Traits>' 中声明的私有成员

英特尔:

没有构造函数“std::basic_ofstream<_Elem, _Traits>::basic_ofstream [with _Elem=char, _Traits=std::char_traits]”的实例与参数列表匹配

有人可以向我解释为什么这不起作用吗?

4

4 回答 4

4

您不能复制流,因为它们的复制构造函数是私有的(或者更具体地说,复制 ctor from basic_ios)。

另请参阅此问题

于 2011-06-18T16:09:56.560 回答
4

STL 流不能被复制构造,那是你的问题。

于 2011-06-18T16:10:49.897 回答
1

As has been said, standard streams are not copiable. However, in C++0x, they are moveable. Depending on what compiler/setting you are using, that is likely the behavior you are seeing. ofstream x(std::ofstream("x")); creates a temporary ofstream, and then moves that temporary into the named ofstream. This is perfectly legal. However, in your code, you define a copy constructor, so no move can take place. Copies are still forbidden, so the compiler stops you.

So, for your class, you would also have to move, not copy. ios_base_adaptor(base_type&& other) : ofstream(std::move(other)) { }

于 2011-06-18T17:33:26.657 回答
0

好的,我想要实现的是创建我派生的任何 basic_ios<> 类的可能性。因此,在我的示例中,我只想为指定的文件创建一个 ofstream。

可以通过以下方式:

template<template<typename, class> class basic_ios_type, typename char_type, class traits_type>
class basic_ios_adaptor<basic_ios_type<char_type, traits_type>>
    : public basic_ios_type<char_type, traits_type>
{
public:
    typedef basic_ios_type<char_type, traits_type> base_type;

    template<class create>
    basic_ios_adaptor(create& create)
    {
        create(static_cast<base_type*>(this));
    }
};

将指针传递给基类应该是安全的,因为在这个阶段它已经被分配和构造了。

用法:

struct construct
{
    void operator()(std::ofstream* o) { 
        *o = std::ofstream("file");
    }
};

construct c;
basic_ios_adaptor<std::ofstream> y(c);

还有其他解决方法吗?

于 2011-06-18T17:24:29.800 回答