当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - What is the difference between "using = " and "using"?

问题描述:

I am aware of the most obvious differences; ie. that using allows you to specify a new name for the type being introduced, but what is the difference between the following two statements:

template <typename T>

class Derived : public X<T>

{

using Base = X<T>;

using Type = typename Base::Type; // statement 1

using typename Base::Type; // statement 2

};

I've noticed that sometimes statement two doesn't work as expected. For example, I might get an error like "error: no member named 'Type' in X".

So how do these statements differ?

网友答案:

using T1 = T2; is new (as of C++11) syntax that provides an alternative to typedef. using Type = typename X::Type; means exactly the same thing as typedef typename X::Type Type;.

using typename X::Type; is older syntax, specifically intended for inheriting members from base classes. Normally, the typename would be redundant, normally you would be able to write using X::Type; instead, but in the case of template base classes, you may need typename to prevent X::Type from being parsed as a non-type member.

An example where they differ is

struct A {
  typedef int i;
};

struct B {
  using i = typename A::i; // valid
  using typename A::i; // invalid, A is not a base class of B
};
网友答案:

The first form introduces a new name for a type, it's alternative syntax for typedef.

The second form redeclares a name for use in the current scope. i.e. it makes a name from another scope usable in the current scope qualifying it, e.g. using std::swap means you can just say swap instead of std::swap.

分享给朋友:
您可能感兴趣的文章:
随机阅读: