gpt4 book ai didi

c++ - 为什么C++可以使用派生结构来实例化其父模板结构并且父模板可以调用子结构的函数?

转载 作者:行者123 更新时间:2023-11-30 03:23:59 25 4
gpt4 key购买 nike

我有一些关于模板结构的问题。

  1. 为什么 C++ 允许派生结构实例化其父模板结构?

  2. 为什么结构Base可以调用static 函数call()通过使用运算符 :: ? (非static是非法的)

  3. TYPENAME(PType)不会替换 PTypeD ,为什么?

请看下面的代码。谢谢!

// Base.h

#pragma once
#include<iostream>

#define TYPENAME(var) #var

template<typename PType>
struct Base
{
public:
inline void Init() {
std::cout <<TYPENAME(PType)<<"\tBase::Init() called" << std::endl;
PType::call();
}
};

struct D :public Base<D> {

public:
inline static void call() {
std::cout <<TYPENAME(D)<<"\tD:call() called" << std::endl;
}
};

//main.cpp
#include<iostream>
#include "Base.h"

int main() {
D d;
d.Init();
std::cin.get();
return 0;
}

最佳答案

Why does C++ allow the derived struct to instantiate its parent template struct?

为什么不呢?您可以实例化 Base<some_type>通过提供 some_type .它没有说像 D 这样的类不能将自己用作 some_type .

Why can the struct Base call the static function call() by using the operator ::? (Not static is illegal)

任何人都可以使用 type::call() 调用静态函数.不限于(或专用于)基类。如果你知道类型和成员名称,你可以调用它。

TYPENAME(PType) doesn't replace the PType with D, why?

TYPENAME是一个宏。在编译器看到代码之前,宏由预处理器处理。

预处理器只看到TYPENAME(PType)所以插入 PType作为文本。

关于c++ - 为什么C++可以使用派生结构来实例化其父模板结构并且父模板可以调用子结构的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50088306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com