-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
git@github.com:PredyDaddy/My_CPP_Note.git
- Loading branch information
1 parent
ff5f99b
commit 9707236
Showing
4 changed files
with
107 additions
and
26 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,34 +1,37 @@ | ||
```cpp | ||
// 子类父类都是类模版 | ||
template <typename T1, typename T2> | ||
class A | ||
{ | ||
// 类的默认访问修饰词是private, 所以这里的x, y是私有属性 | ||
// 如果向指定为公有的,需要修改饰词为public | ||
T1 x; | ||
T2 y; | ||
template <typename T> | ||
struct HasValue { | ||
template <typename U> | ||
static std::true_type test(decltype(&U::value)); | ||
|
||
template <typename U> | ||
static std::false_type test(...); | ||
|
||
static constexpr bool value = decltype(test<T>(nullptr))::value; | ||
}; | ||
|
||
template <typename T1, typename T2> | ||
class B : public A<T2, T1> | ||
{ | ||
T1 x1; | ||
T2 x2; | ||
template <typename T> | ||
typename std::enable_if<HasValue<T>::value>::type | ||
printValue(T arg) { | ||
std::cout << "Value: " << arg.value << std::endl; | ||
} | ||
|
||
struct MyStruct { | ||
int value = 42; | ||
}; | ||
|
||
template<typename T> | ||
class C : public B<T, T> | ||
{ | ||
T x3; | ||
struct MyOtherStruct { | ||
float otherValue = 3.14f; | ||
int value = 43; | ||
}; | ||
|
||
int main() | ||
{ | ||
// B中的T1和A中的T1 泛指int, B中的T2,A中的T1 泛指float | ||
B<int, float> b; | ||
int main() { | ||
MyStruct s; | ||
MyOtherStruct os; | ||
|
||
printValue(s); // 输出:Value: 42 | ||
|
||
// 这样A,B,C中全部泛指类型都是int | ||
C<int> c; | ||
return 0; | ||
// 下面这行代码会在编译时出现错误,因为MyOtherStruct类型不满足HasValue的限定条件 | ||
printValue(os); | ||
} | ||
``` | ||
``` |