我有一个输入类,它有一个应该以函数作为参数的方法。
#include "pixelGameEngine.h"
#include <functional>
class Input
{
public:
Input() = default;
Input(const Input&) = delete;
Input& operator=(const Input&) = delete;
public:
static void OnDPress(olc::PixelGameEngine* pge, std::function<void()> DoIteration) noexcept
{
if (pge->GetKey(olc::D).bPressed)
{
DoIteration();
}
}
};
Run Code Online (Sandbox Code Playgroud)
我有一个三角形处理器类应该调用该函数。
#include "pixelGameEngine.h"
#include "input.h"
#include <functional>
class TriangleProcessor
{
//...
void DoIteration() noexcept{};
Input input;
void Run(olc::PixelGameEngine* pge)
{
Input::OnDPress(pge, DoIteration);
}
}
Run Code Online (Sandbox Code Playgroud)
但我"no suitable constructor exists to convert from "void () to "std::function<void ()>"在网上遇到了一个错误Input::OnDPress(pge, DoIteration);,下面有一个红色的波浪线DoIteration。
我在看书时遇到了可变参数模板,并认为实现一个 python 风格的print函数会很酷。
这是代码。
#include <iostream>
#include <string>
#define None " "
template<typename T, typename... Tail>
void print(T head, Tail... tail, const char* end = "\n")
{
std::cout << head << end;
if constexpr (sizeof...(tail) > 0)
{
print(tail..., end);
}
}
int main()
{
// Error: no instance of function template "print" matches the argument list
print("apple", 0, 0.0f, 'c', true);
// Error: no instance of function template "print" matches the argument list
print("apple", 0, …Run Code Online (Sandbox Code Playgroud) 在我目前阅读的文章和书籍中,只有在持有指针的类中完成移动操作。这些操作从根本上通过交换指针并将旧指针设置为nullptr. 但是当std::move()使用默认赋值运算符在没有任何指针的情况下调用类时会发生什么?例子:
#include <iostream>
class MyClass
{
public:
MyClass(int x) : x(x) {}
int x = 0;
MyClass& operator=(MyClass&& other) = default;
};
int main()
{
MyClass a{ 10 };
MyClass b{ 20 };
std::cout << a.x << '\n';
a = std::move(b);
std::cout << a.x << '\n';
}
Run Code Online (Sandbox Code Playgroud)
结果是
10
20
Run Code Online (Sandbox Code Playgroud)
它似乎有效,但如何?它与普通的赋值运算符有什么不同吗?
出于好奇,我查看了如何std::is_pointer实现并看到了这样的东西(多个重载之一):
template <class _Ty>
_INLINE_VAR constexpr bool is_pointer_v<_Ty*> = true;
Run Code Online (Sandbox Code Playgroud)
如果我复制并粘贴到我的代码中并编译,则表示 constexpr 在这里无效。怎么了?
是否可以像我们一样std::is_pointer实现结构体?std::is_reference(不是我愿意,只是好奇所以请不要来找我)
MRE 与 msvc 2019:
template <class _Ty>
inline constexpr bool is_pointer_v<_Ty*> = true;
int main()
{
}
Run Code Online (Sandbox Code Playgroud)
--
Error: error C7568: argument list missing
after assumed function template 'is_pointer_v'
Run Code Online (Sandbox Code Playgroud)