如何在 C++ 赋值中命名 class 标识符?

How to name class identifier in assignment in c++?

从这里:Difference between 'struct' and 'typedef struct' in C++?,我发现如果存在名称冲突(例如,如果 class 名称与函数名称相同),我需要 class 标识符:

#include <iostream>

using namespace std;

class foo
{
public:
    foo() {}
    operator char const *() const
    {
        return "class";
    }
};

char const *foo()
{
    return "function\n";
}

int main()
{
    char const *p;
    p = class foo(); //this gets error
    cout << p << '\n';
    return 0;
}

输出:

error: expected primary-expression before ‘class’
     p = class foo();

这里的主要表达式是什么?如何识别 class 而不是函数?我希望它打印 class 而不是 function。如何操作?

可能的解决方案之一:

using bar = class foo;
p = bar();
int main()
{
    char const *p;
    struct foo f;
    p = static_cast<char const*>(f);
    cout << p << '\n';
    return 0;
}

顺便说一下,the answer you link 提到可以使用 typedef class foo foo; 触发同名函数的编译器错误。拥有 class 和同名函数并不是我们想要的,而是您需要稍微解决一下语言允许的事实。不要错过最后一段:

I can't imagine why anyone would ever want to hide a class name with a function or object name in the same scope as the class. The hiding rules in C were a mistake, and they should not have been extended to classes in C++. Indeed, you can correct the mistake, but it requires extra programming discipline and effort that should not be necessary.

如果您控制了该函数或 class 您一定要重命名它或将它放在命名空间中。

我找到了两个 g++clang 都接受的解决方案。但是,我不知道它们是否是标准 C++。

  • 统一初始化

     cout << (class foo){} << "\n";
    
  • 使用助手

    template <typename T, typename ...Args>
    T ctor(Args&& ...args) {
        return T{ std::forward<Args>(args) ... };
    }
    
    
    // ...
    
    cout << ctor<class foo>() << "\n";