正如预期的那样,以下代码不会编译
#include <iostream>
class A
{
public:
A() = default;
~A() = default;
A(const A&) = delete;
A(A&&) = delete;
A& operator=(const A&) = delete;
A& operator=(A&&) = delete;
A& operator<<(const int i)
{
std::cout << "operator<< called" << std::endl;
return *this;
}
};
void foo(A&& a)
{
std::cout << "foo called" << std::endl;
}
int main()
{
A a; a << 14;
foo(std::move(a)); // works fine
foo(A() << 14); // does not compile
return 0;
}
Run Code Online (Sandbox Code Playgroud)
将A类改为
class A …Run Code Online (Sandbox Code Playgroud) 在c ++中,隐式地完成了不同类型的转换.例如,int可以将类型的对象分配给const int(如下面代码中主函数的第一行中所做的那样).
现在我想检查运行时的可转换性,因为我有一个可以添加类型的结构,后来我想检查给定类型,如果结构中存储的类型之一可以转换为给定类型.
这是我到目前为止提出的:
#include <iostream>
#include <vector>
struct bar { virtual void dummy() {} };
template<typename T> struct foo : public bar { virtual void dummy() {} };
int main() {
int i1 = 1;
const int i2 = i1;
std::vector<bar*> bars;
bar* t1 = new foo<int>; bars.push_back(t1);
bar* t2 = new foo<int const>; bars.push_back(t2);
foo<int const>* t3 = dynamic_cast<foo<int const>*>(bars[0]);
std::cout << t3 << std::endl;
foo<int const>* t4 = dynamic_cast<foo<int const>*>(bars[1]);
std::cout << …Run Code Online (Sandbox Code Playgroud) 这个问题是这个问题的后续:模板化类 的模板化构造函数的显式模板专业化另一个问题中给出的答案当然是正确的,但结果证明我并没有问我想问什么 - 所以这里是一个新问题:
考虑以下代码:
template<typename First, typename ... Rest> class var {
public:
var() {
std::cout << "default" << std::endl;
}
var(const var& v) {
std::cout << "copy" << std::endl;
}
var(var&& v) {
std::cout << "move" << std::endl;
}
template<typename T>
var(const T& t) {
std::cout << "general lvalue" << std::endl;
}
template<typename T>
var(T&& t) {
std::cout << "general rvalue" << std::endl;
}
};
int main()
{
var<int> i0; // expect 'default' -> get …Run Code Online (Sandbox Code Playgroud) 考虑以下程序:
#include <iostream>
template<typename T> void f1(T& v)
{
std::cout << "f1: can call g" << std::endl;
v.g();
}
template<typename T> void f2(T& v) requires requires (T& v) { v.g(); }
{
std::cout << "f2: can call g" << std::endl;
v.g();
}
template<typename T> void f2(T&) requires (!requires (T& v) { v.g(); })
{
std::cout << "f2: cannot call g" << std::endl;
}
class A
{
public: // if commented out, f2 will not call g anymore
void g()
{ …Run Code Online (Sandbox Code Playgroud)