gpt4 book ai didi

c++ - 为什么不需要资格?

转载 作者:IT老高 更新时间:2023-10-28 22:59:01 25 4
gpt4 key购买 nike

好的,我会发布完整的程序,即使它有多余的东西并且有问题的代码是死代码……

#include <iostream>
#include <fstream>

namespace detail {
// Solution by Johannes Schaub alias litb
// http://groups.google.com/group/comp.std.c++/browse_thread/thread/b567617bfccabcad
template<int> struct D {};
typedef char yes[1];
typedef char no[2];

template< class T, class U >
yes& f( int, D< sizeof T(*(U*)0) >* = 0 );

template< class T, class U >
no& f( ... );

template< class To, class From >
struct IsExplicitlyConvertible
{
enum{ yes = (sizeof detail::f< To, From >(0) == sizeof( detail::yes ) ) };
};

bool const streamsSupportWindows =
IsExplicitlyConvertible< std::ofstream, wchar_t const* >::yes;
}

class InFStream
: public std::ifstream
{
public:
InFStream() {}
explicit InFStream(
char const* filename,
ios_base::openmode mode = ios_base::in | ios_base::out
)
: std::ifstream( filename, mode )
{}
};

int main()
{
using namespace std;
cout << (detail::streamsSupportWindows
? "Windows-enabled"
: "Ach, no Windows support"
) << endl;
}

这与 MSVC 和 g++ 编译得很好。但是在 InFStream 类中,为什么我不需要限定 ios_base?或者,同样的问题,为什么我需要在构造函数初始化列表中使用 ifstreamstd:: 限定?

最佳答案

区别在于ifstream不作为注入(inject)的类名可见,因为它是 typedef 的名称,而不是 class 的名称.因此,它作为来自基类的注入(inject)类名不可见。

ios_base是一个真正的类名,它是使用它的类的(基类的)基类,因此作为注入(inject)类名是可见的。

例如

namespace X
{
class A {};
template<class> class Z {};
typedef Z<char> B;
}

class C : public X::A
{
C() : A() {} // OK, A is visible from the base class
};

class D : public X::B
{
D() : B() {} // Error, B is a typedef,
// : X::B(), : Z<char>() or even : Z() can be used.
};

在您的示例中,而不是 std::ifstream ,可以使用不合格的basic_ifstream反而。 (或 basic_ifstream<char>basic_ifstream<char, std::char_traits<char> > 但这些并不能真正节省任何打字或帮助清晰。)

关于c++ - 为什么不需要资格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7868009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com