相关疑难解决方法(0)

将内联关键字与模板一起使用是否有意义?

由于模板是在头文件中定义的,编译器能够确定内联函数是否有利,它是否有意义?我听说现代编译器更好地知道何时内联函数并忽略inline提示.


编辑:我想接受这两个答案,但这是不可能的.为了解决这个问题,我接受了菲涅耳的回答,因为它收到了大多数选票并且他是正式的,但正如我在评论中所提到的,我从不同的角度考虑Puppy组件10的答案也是正确的. .

问题出在C++语义中,在inline关键字和内联的情况下并不严格.Phresnel说"如果你的意思是写内联",但实际意义inline并不明确,因为它从原来的意义演变为"阻止编译人员讨论ODR违规"的指令,正如Puppy所说.

c++ templates inline

110
推荐指数
3
解决办法
6万
查看次数

定义模板类相同类型的静态 constexpr 成员

非模板类的类似问题

对于模板类,

template <typename T>
struct Test {
    T data;

    static const Test constant;
};
Run Code Online (Sandbox Code Playgroud)

定义特殊类型的成员变量时没问题static constexpr

template <>
inline constexpr Test<int> Test<int>::constant {42};
Run Code Online (Sandbox Code Playgroud)

https://godbolt.org/z/o4c4YojMf


static constexpr当直接从模板类定义成员而不实例化时,编译器的结果会有所不同:

template <typename T>
inline constexpr Test<T> Test<T>::constant {42};
Run Code Online (Sandbox Code Playgroud)

https://godbolt.org/z/M8jdx3WzM

GCC编译。
clang忽略constexpr定义中的说明符。
MSVC.../std:c++17效果很好,但/std:c++20由于重新定义而被拒绝。


我了解到constexpr可以应用于定义变量或变量模板

在这个例子中,哪一个是正确的?为什么?

c++ language-lawyer c++17 c++20

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

我可以在类外初始化一个 `constexpr static` 成员吗?

我正在使用可变宽度的通信格式。处理它的结构看起来像这样:

struct Header
{
  int msgType = -1, len;

  Header() { len = sizeof(*this); }
};

struct A : public Header
{
  int x; char y;

  A() { msgType = 1; len = sizeof(*this); }
};

// Further structs B, C, ... declared along the same lines
Run Code Online (Sandbox Code Playgroud)

我想要一个constexpr static成员Header::MAX_SIZE,它给出任何这些派生类的最大大小,例如,这样我就可以分配一个缓冲区,保证可以容纳任何此类数据包。所以我想做类似的事情

struct Header
{
  int msgType = -1, len;

  constexpr static std::size_t MAX_SIZE;

  Header() { len = sizeof(*this); }
};

// ... declaration of subclasses ...

inline Header::MAX_SIZE …
Run Code Online (Sandbox Code Playgroud)

c++

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

标签 统计

c++ ×3

c++17 ×1

c++20 ×1

inline ×1

language-lawyer ×1

templates ×1