这个定义有效:
const auto &b{nullptr};
Run Code Online (Sandbox Code Playgroud)
虽然失败了:
auto *b{nullptr};
Run Code Online (Sandbox Code Playgroud)
我试图在Visual C++,GCC和Clang中编译它.他们都抱怨"不能推断出类型".
在第二种情况下,不b应该推断出有某种类型的std::nullptr_t?
template <class T>
void Yeap(T);
int main() {
Yeap(0);
return 0;
}
template <class T>
void YeapImpl();
struct X;
template <class T>
void Yeap(T) {
YeapImpl<X>(); // pass X to another template
}
template <class T>
void YeapImpl() {
T().foo();
}
struct X {
void foo() {}
};
Run Code Online (Sandbox Code Playgroud)
请注意,struct X直到最后才定义.我曾经相信所有使用过的名字必须在实例化时完成.但是在这里,编译器如何在定义之前将其视为完整类型?
我已经检查了cppreference中的依赖名称和函数模板实例化的绑定规则和查找规则,但是没有一个能够解释这里发生的事情.
此代码段无法在MSVC,Clang和Gcc中编译(它们提供不同的错误消息):
int foo(int a, int b) {
return a + b;
}
template <class Ret, class A, class B>
void foo(Ret (*)(A, B)) {
}
int main() {
foo(foo);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这不应该编译吗?我无法理解为什么它无法解析重载函数或推断模板参数.欢迎任何帮助,谢谢.
PS:如果替换模板void foo(int (*)(int, int)),或者我们重命名模板foo以避免超载,则编译它.
#include <tuple>
struct X {
int i = 0;
friend constexpr bool operator<(const X &l, const X &r) noexcept {
return l.i < r.i;
}
};
struct Y {
int i = 0;
constexpr operator bool() const noexcept {
return i != 0;
}
friend constexpr bool operator<(const Y &l, const Y &r) noexcept {
return l.i < r.i;
}
};
int main() {
constexpr X a{1}, b{2};
static_assert(std::tie(a) < std::tie(b));
constexpr Y c{1}, d{2};
static_assert(c < d);
// assert …Run Code Online (Sandbox Code Playgroud) 我已经阅读了cppreference 的评估顺序,但我找不到任何与此情况相关的规则.这是否意味着之前没有顺序关系,或者我错过了什么?谢谢.
以下代码段给出了一个示例.
#include <memory>
struct Foo {
void func(std::unique_ptr<Foo>) {}
};
int main() {
auto ptr = std::make_unique<Foo>();
ptr->func(std::move(ptr)); // Is this valid?
return 0;
}
Run Code Online (Sandbox Code Playgroud) 检查是否可以在对象上调用成员函数/自由函数的方法是:
#include <type_traits>
#include <utility>
template <class T, class = void>
struct HasMember : std::false_type {};
template <class T>
struct HasMember<T, std::void_t<decltype(std::declval<T>().Foo())>> : std::true_type {};
template <class T, class = void>
struct HasFreeFoo : std::false_type {};
template <class T>
struct HasFreeFoo<T, std::void_t<decltype(Foo(std::declval<T>()))>> : std::true_type {};
struct A { void Foo() {} };
struct B : A {};
struct C : B {};
void Foo(const A &) {}
int main() {
static_assert(HasMember<C>::value, "");
static_assert(HasFreeFoo<C>::value, "");
}
Run Code Online (Sandbox Code Playgroud)
但正如示例所示,
CFoo被认为已经A …c++ ×6
c++17 ×3
templates ×3
c++20 ×2
auto ×1
c++14 ×1
expression ×1
nullptr ×1
side-effects ×1