相关疑难解决方法(0)

自动与字符串文字

#include <iostream>
#include <typeinfo>

int main()
{
    const char a[] = "hello world";
    const char * p = "hello world";
    auto x = "hello world";

    if (typeid(x) == typeid(a))
        std::cout << "It's an array!\n";

    else if (typeid(x) == typeid(p))
        std::cout << "It's a pointer!\n";   // this is printed

    else
        std::cout << "It's Superman!\n";
}
Run Code Online (Sandbox Code Playgroud)

x当字符串文字实际上是数组时,为什么推断为指针?

窄字符串文字的类型为"数组n const char "[2.14.5字符串文字[lex.string]§8]

c++ type-inference string-literals auto c++11

20
推荐指数
2
解决办法
3405
查看次数

可以将变量重新声明为推导为相同类型的auto吗?

标准是否允许以下​​内容?

#include <iostream>

extern int a;
auto a = 3;

int main(int, char**)
{
    std::cout << a << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

clang接受代码. g ++抱怨声明冲突.

c++ extern language-lawyer auto c++11

16
推荐指数
1
解决办法
424
查看次数

外部函数指针声明和类型推断定义

我最近收到的代码被clang ++接受但不是g ++,我想知道哪一个是正确的.

再现行为的极简主义代码非常短并且单独说话,所以我认为解释会不必要地复杂化.

这是一个包含extern指针声明的标头:

//(guards removed for simplicity) :
#include <type_traits>

using ptr_func = std::add_pointer<void()>::type;

extern ptr_func pointer;
Run Code Online (Sandbox Code Playgroud)

以下是实现所需指向函数的源代码:

#include "function.hh"

void foo() {}

auto pointer = &foo;
Run Code Online (Sandbox Code Playgroud)

gcc生成的错误如下:

g++ -c function.cc -std=c++14
function.cc:5:6: error: conflicting declaration ‘auto pointer’
 auto pointer = &foo;
      ^
In file included from function.cc:1:0:
function.hh:5:17: note: previous declaration as ‘void (* pointer)()’
 extern ptr_func pointer;
                 ^
Run Code Online (Sandbox Code Playgroud)

Clang接受此代码时没有任何错误/警告.并通过以下方式替换指针定义:

decltype(foo)* pointer = &foo;
Run Code Online (Sandbox Code Playgroud)

被gcc接受.

在我看来,clang是对的,但我不确定所以我想知道clang是否过于宽松或者gcc是否应该接受它.

c++ function-pointers c++11

12
推荐指数
1
解决办法
437
查看次数

如何初始化静态成员而不重复其类型

假设我们有以下课程:

class A {
    static SomeLongType b;
};
Run Code Online (Sandbox Code Playgroud)

现在我们必须在适当的cpp文件中初始化它.我可以想到以下几种方式:

SomeLongType A::b{}; // repetition of SomeLongType
decltype(A::b) A::b{}; // A::b written two times
Run Code Online (Sandbox Code Playgroud)

对我来说,两者似乎都很麻烦.有没有更好的办法?

c++ c++11

5
推荐指数
1
解决办法
185
查看次数