标签:新特性 编译 void 基类 include 模板 关系 err 可变
先来看 using 声明在类中的应用:
代码1
#include <iostream>
using namespace std;
struct A {
void f(int) {cout << "A::f(int)" << endl;}
};
struct S : A {
};
int main()
{
S s;
s.f(1); // A::f(int)
}
代码2
#include <iostream>
using namespace std;
struct A {
void f(int) {cout << "A::f(int)" << endl;}
};
struct S : A {
void f(double) {cout << "S::f(double)" << endl;}
};
int main()
{
S s;
s.f(1); // S::f(double)
}
代码3
#include <iostream>
using namespace std;
struct A {
void f(int) {cout << "A::f(int)" << endl;}
};
struct S : A {
using A::f;
void f(double) {cout << "S::f(double)" << endl;}
};
int main()
{
S s;
s.f(1); // A::f(int)
}
代码4
#include <iostream>
using namespace std;
struct A {
void f(int) {cout << "A::f(int)" << endl;}
};
struct B {
void f(double) {cout << "S::f(double)" << endl;}
};
struct S : A, B {
};
int main()
{
S s;
s.f(1); // compile error
}
代码5
#include <iostream>
using namespace std;
struct A {
void f(int) {cout << "A::f(int)" << endl;}
};
struct B {
void f(double) {cout << "S::f(double)" << endl;}
};
struct S : A, B {
using A::f;
using B::f;
};
int main()
{
S s;
s.f(1); // A::f(int)
}
在 C++17 中多个 using 声明可以通过逗号连接起来。
代码6
#include <iostream>
using namespace std;
struct A {
void f(int) {cout << "A::f(int)" << endl;}
};
struct B {
void f(double) {cout << "S::f(double)" << endl;}
};
struct S : A, B {
using A::f, B::f; // C++17
};
int main()
{
S s;
s.f(1); // A::f(int)
}
通过使用加了 ... 的 using 声明,可以将变长模板参数类型中的using 声明转化为多个用逗号合成的变长 using 声明。
#include <iostream>
#include <string>
using namespace std;
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
int main()
{
overloaded s{
[](int){cout << "int" << endl;},
[](double){cout << "double" << endl;},
[](string){cout << "string" << endl;},
};
s(1); // int
s(1.); // double
s("1"); // string
}
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };template<class... Ts>:overloaded 类的模板参数为可变长的参数包 Ts。template<class T1, class T2, ..., class TN>struct overloaded : Ts...:overloaded 类的基类为参数包 Ts 内所有的参数类型。struct overloaded : T1, T2, ..., TNusing Ts::operator()...;:这是一个变长 using 声明。using T1::operator(), T1::operator(), ..., TN::operator(), ;template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;overloaded {a1, a2, ..., an} 的类型就是 overloaded<T1, T2, ..., TN>。overloaded s{[](int){cout << "int" << endl;},[](double){cout << "double" << endl;},[](string){cout << "string" << endl;},};overloaded<T1, T2, T3>,其中T1, T2, T3为3个lambda参数的类型。标签:新特性 编译 void 基类 include 模板 关系 err 可变
原文地址:https://www.cnblogs.com/zwvista/p/9256655.html