从模板参数派生并调用其副本构造函数

| 请考虑以下代码:
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
Visual C ++:   \'std :: basic_ios <_Elem,_Traits> :: basic_ios \'   :无法访问私人会员   在课堂上宣告   \'std :: basic_ios <_Elem,_Traits> \' 英特尔:   没有构造函数的实例   \“ std :: basic_ofstream <_Elem,   _Traits> :: basic_ofstream [带有_Elem = char,_Traits = std :: char_traits] \“与参数列表匹配 有人可以向我解释为什么这行不通吗?     
已邀请:
        您无法复制流,因为它们的复制构造函数是私有的(或更具体地说,是来自
basic_ios
的复制ctor)。 另请参阅此问题。     
        STL流无法复制构造,这就是您的问题。     
        如前所述,标准流不可复制。但是,在C ++ 0x中,它们是可移动的。根据您使用的编译器/设置,这可能是您所看到的行为。
ofstream x(std::ofstream(\"x\"));
创建一个临时
ofstream
,然后将其移动到命名的
ofstream
中。这是完全合法的。但是,在您的代码中,您定义了一个复制构造函数,因此无法进行任何移动。仍然禁止复制,因此编译器会阻止您。 因此,对于您的班级,您还必须移动而不是复制。
ios_base_adaptor(base_type&& other) : ofstream(std::move(other)) { }
    
        好的,我想要实现的是可以创建派生自我的basic_ios <>类的可能性。因此,在我的示例中,我只想为指定的文件创建一个流。 可以通过以下方式进行:
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);
还有其他解决方法吗?     

要回复问题请先登录注册