8

I'm stuck with templates and scope resolution operator. I found these line in a file, I'm not able to figure out why we are using :: in front of a template function call, as of my knowledge we can only use :: in front of variables when refering to a global variable. Any Idea will be helpful

#define CREATE_AND_DECODE_TYPE(Type, buffer, pType) \
    ::CreateAndDecodeType<Type>(buffer, pType, throwVarBindExceptions, static_cast<Type *>(NULL))
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Vikram Singh
  • 273
  • 1
  • 3
  • 10

1 Answers1

16

The scope resolution operator :: (at the beginning) forces the compiler to find the identifier from the global scope, without it the identifier is found relative to the current scope.

namespace X
{
    namespace std
    {
        template<typename T>
        class vector {};
    }

    std::vector<int>     x;       // This is X::std::vector
    ::std::vector<int>   y;       // This is the std::vector you normally expect (from the STL)
}
Martin York
  • 257,169
  • 86
  • 333
  • 562
  • 2
    @RaHuL: **NO**. If you use `std::vector` (without the prefex ::) the search is **relative** to the current scope. Which means the compiler will check `X::std::vector` first which it finds, Since it finds this version it does not check the for one in the global scope. **NOTE** normally you don't have a namespace `std` inside the current namespace so the search would start in X the fall back to the global scope and find the `std` in the global namespace but in the situation above you see there is a `std` inside `X`. – Martin York Feb 27 '20 at 18:00
  • @RaHuL: If you use the prefix `::` then the compiler search is an absolute search where it only looks from the global namespace. – Martin York Feb 27 '20 at 18:00
  • How often do you come across a nested namespace called `std` in practice? – Aykhan Hagverdili Aug 12 '20 at 15:19
  • @Ayxan This has nothing to do with `std`. I just used that as a trivial example of the issue. How about the namespace `util`? – Martin York Aug 13 '20 at 00:55
  • I am asking because I've seen it done with `std` quite a lot, and I was wondering if `::std::string` is actually any safer than `std::string` in practice. – Aykhan Hagverdili Aug 13 '20 at 06:02
  • 1
    @Ayxan It is safer (nothing unsafe with being explicit). How much safer, I have no idea (or numbers). It will depend on the quality of the other libraries you use I suppose. If you are writing your own app I doubt it will make much difference. If you are writing libraries that other people use (or use incorrectly) then it may save them. – Martin York Aug 13 '20 at 22:45
  • 1
    PS. I have seen the something like the above exactly once (many years ago) in 30 years. It was done to override something from the standard library without going into the code and and doing a cut/paste to change the name of the type (as that was error prone). – Martin York Aug 13 '20 at 22:48