相关疑难解决方法(0)

`constexpr`和`const`之间的区别

constexpr和之间有什么区别const

  • 我什么时候才能只使用其中一个?
  • 我何时可以同时使用这两种方法?如何选择?

c++ const constexpr c++11

540
推荐指数
9
解决办法
19万
查看次数

警告:ISO C++禁止将字符串常量转换为'char*'以获取静态`constexpr char*`数据成员

为什么此代码会返回警告

警告:ISO C++禁止将字符串常量转换为'char*'[ - WRrite-strings]

如果

在对象声明或非静态成员函数中使用的constexpr说明符(直到C++ 14)暗示const.函数或静态成员变量(自C++ 17)声明中使用的constexpr说明符暗示内联.

(cppreference.com)

#include <cassert>    
#include <string>    
#include <iostream>    

struct A     
{    
    // warning: ISO C++ forbids converting a string constant to ‘char*’    
    static constexpr char* name_ = "A";                           
    static constexpr char* name() { return name_; };             
};                                             

int main()    
{};    
Run Code Online (Sandbox Code Playgroud)

如果我添加一个constconstexpr,警告消失了:

#include <cassert>    
#include <string>    
#include <iostream>   



struct A     
{    
    static constexpr const char* name_ = "A";    
    static constexpr const char* name() { return name_; }; …
Run Code Online (Sandbox Code Playgroud)

c++ static constexpr c++11

31
推荐指数
2
解决办法
6634
查看次数

constexpr 真的意味着 const 吗?

比较以下内容:

我在一个类中有一个静态成员,要么是const constexpr要么只是constexpr. 根据MS Docs上的解释,constexpr 意味着常量:

所有 constexpr 变量都是 const。

然而,这会在 gcc 8.4 中发出警告:

#include <iostream>
#include <string>

struct some_struct
{
    static constexpr char* TAG = "hello";
    void member() {
        printf("printing the tag %s", TAG);
    }  
};

int main()
{
    some_struct A;
    A.member();
}
Run Code Online (Sandbox Code Playgroud)

虽然这不会:

#include <iostream>
#include <string>

struct some_struct
{
    static const constexpr char* TAG = "hello";
    void member() {
        printf("printing the tag %s", TAG);
    }  
};

int main()
{
    some_struct A; …
Run Code Online (Sandbox Code Playgroud)

c++ constants static-members constexpr c++17

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

为什么我必须使用const和constexpr作为静态类函数?

我正在尝试了解在测试更改时我所看到的内容.该平台是带有GCC 4.8的openSUSE 42,但它可能会影响其他人.测试代码和错误如下.

$ cat test.cxx 
#include <string>

#if (__cplusplus >= 201103L)
#  define STATIC_CONSTEXPR static constexpr
#  define CONSTEXPR constexpr
#else
#  define STATIC_CONSTEXPR static const
#  define CONSTEXPR
#endif

struct Name
{
  STATIC_CONSTEXPR char* GetName() {return "XXX";}
};

int main(int argc, char* arv[])
{
  const char* name = Name::GetName();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

和:

$ g++ -O3 -std=c++11 test.cxx -o test.exe
test.cxx: In static member function ‘static constexpr char* Name::GetName()’:
test.cxx:13:44: warning: deprecated conversion from string constant to ‘char*’ …
Run Code Online (Sandbox Code Playgroud)

c++ constexpr c++11

0
推荐指数
1
解决办法
295
查看次数

标签 统计

c++ ×4

constexpr ×4

c++11 ×3

c++17 ×1

const ×1

constants ×1

static ×1

static-members ×1