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

标签 c++ templates inheritance static

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

  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/

相关文章:

c++ - 由静态方法(或工厂(?))创建的 boost python 对象中的虚拟覆盖

c++ - 当使用等于字符串长度的 "pos"调用 str.erase 时会发生什么?

c++ - 声明模板的共享指针

php - 这是一个 php 错误 : subclasses must declare private methods with the same signature as in parent class

ruby-on-rails - rails模型的继承

c# - 确定一个类是否实现了一个非常具体的接口(interface)

c++ - 如何验证运行时失败是否是由于生成的线程过多造成的?

c++ - 如何创建具有最大长度的 vector ?

c++ - 使用数组参数的函数特化

c++ - 模板中无限量的泛型类型?