3

I do not understand below usage of using in C++. What's difference with typedef? Could someone explain it with some example?

template<typename DataType> class DataWriter { using ObjType = std::function<void(DataType)> // ... } 
2
  • It's a syntactic sugar brought by C++11. See this post. Commented Jan 31, 2015 at 1:00
  • 1
    In this particular case, it's syntactic sugar. It has other, awesome, uses in addition that typedef doesn't do. Commented Jan 31, 2015 at 1:02

2 Answers 2

4

There is no difference in your example to a typedef.

Those are identical:

typedef int a; using a = int; 

In general, it is more versatile though, which is the reason it was introduced:

  • It can be templated.

    template<class X> using smart = std::unique_ptr<X>; 
  • It can be used to import symbols into the current scope.

    struct Derived : Base { using Base::Fun; }; 
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think the asker wanted an enumeration of all scenarios were the keyword using appears. He was talking about alias declarations in particular.
@Columbo: Thanks for the edit. And I don't think the OPs focus is quite that narrow, even if that was the example he gave.
Thanks all. Firstly, I want to know this "using" usage, secondly I also want to know the reason why C++ 11 introduce this language sugar, I guess there are some reasons.
2

There is no difference. [dcl.typedef]/2:

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name [..]. It has the same semantics as if it were introduced by the typedef specifier.

I.e.

using ObjType = std::function<void(DataType)>; 

Is equivalent to

typedef std::function<void(DataType)> ObjType; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.