小编Lin*_*k64的帖子

使用 C++20 概念来避免 std::function

过去,当我想要一个回调作为函数参数时,我通常决定使用std::function. 在我绝对从不使用捕获的极少数情况下,我使用 atypedef作为函数声明。

所以,通常我的带有回调参数的声明看起来像这样:

struct Socket
{
  void on_receive(std::function<void(uint8_t*, unsigned long)> cb);
}
Run Code Online (Sandbox Code Playgroud)

但是,据我所知,std::function实际上在运行时做了一些工作,因为必须解析 lambda 并将其捕获到std::function模板并移动/复制它的捕获(?)。

阅读有关新的 C++ 20 特性的内容时,我认为我可以利用概念来避免std::function对任何可行的函子使用和使用受约束的参数。

这就是我的问题出现的地方:因为我想在将来的某个时候使用回调函子对象,所以我必须存储它们。由于我的回调没有确定的类型,我最初的想法是复制(最终在某个时候移动)函子堆并使用 astd::vector<void*>来记录我离开它们的位置。

template<typename Functor>
concept ReceiveCallback = std::is_invocable_v<Functor, uint8_t*, unsigned long>
                       && std::is_same_v<typename std::invoke_result<Functor, uint8_t*, unsigned long>::type, void>
                       && std::is_copy_constructible_v<Functor>;
struct Socket
{
  std::vector<void*> callbacks;

  template<ReceiveCallback TCallback>
  void on_receive(TCallback const& callback)
  {
    callbacks.push_back(new TCallback(callback));
  }
}

int main(int argc, char** argv)
{
  Socket* sock;
  // [...] inialize socket …
Run Code Online (Sandbox Code Playgroud)

c++ lambda c++-concepts c++20

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

Z value always 1 or -1 when using `glm::perspective`

I'm trying to teach myself the ways for 3D programming with OpenGL, however I am struggling with some things, especially projection matrices.

I defined some vertices for a cube and successfully handed them to my graphics processor. The cube goes from xyz -0.5 to xyz 0.5 respectively, which gets rendered fine.

To move it into my world coordinate system, I am using this model matrix:

auto model = glm::mat4(
    glm::vec4(1, 0, 0, 0),
    glm::vec4(0, 1, 0, 0),
    glm::vec4(0, 0, 1, …
Run Code Online (Sandbox Code Playgroud)

c++ opengl glsl glm-math

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

标签 统计

c++ ×2

c++-concepts ×1

c++20 ×1

glm-math ×1

glsl ×1

lambda ×1

opengl ×1