4

At Calling a static method by repeating the object name, I see the following code.

struct foo {
  static foo& instance() {
    static foo f;
    return f;
  }
};

And

foo::foo::foo::instance();

works fine.

However, at expected type-specifier and cannot convert ‘int*’ in initialization, I see the following code:

namespace ASP
{
    class ASp
    {
        public:
            ASp();
            ASp(FILE* fp);  
    };
}

But

using namespace ASP;
ASp* asp = new ASp::ASp();

fails to compile in g++ 4.8.2 and Visual Studio 2010.

g++ reports:

error: expected type-specifier
 ASp* asp = new ASp::ASp();

Visual Studio reports:

error C2061: syntax error : identifier '{ctor}'

Why does injected class name work for the first case and not for the second case?

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • The compiler doesn't know whether asp denotes a namespace or a class. Use asp::asp instead. – cqdjyy01234 Dec 03 '14 at 07:43
  • @user1535111, The namespace is `ASP`, with an uppercase `P`. The class name is `ASp`, with a lowercase `p`. – R Sahu Dec 03 '14 at 15:43
  • My mistake! But both examples cannot compile under vs2015 preview and give the same errors! With typename added to the 2nd example, both are fine under gcc! – cqdjyy01234 Dec 04 '14 at 01:27

1 Answers1

4

I think GCC provides a rather useful hint:

error: expected type-specifier

The new operator expects a type name immediately afterwards, not a constructor name.

The expression ASp::ASp can refer to either the constructor of the type or the type itself. However, C++ has rules on how this ambiguity is resolved: in your case it defaults to the constructor, not the type. In order to force this to be resolved as a type, you must prefix it with typename (thanks ooga!), struct, or class (or access its member using :: like in your first example):

using namespace ASP;
ASp* asp = new class ASp::ASp();
Rufflewind
  • 8,545
  • 2
  • 35
  • 55