gpt4 book ai didi

java - 在 C++ 中的模板参数上调用静态函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:03:54 25 4
gpt4 key购买 nike

以下 Java 代码在代表 Printer 的派生类的泛型参数 T 上调用静态方法 printText(text)。是否有可能在 C++ 中实现完全相同的行为?如果是,如何?

public class Printer {

public static void printText(String text) {
System.out.println(text);
}

public static <T extends Printer>void print(String text) {
T.printText(text);
}

public static void main(String[] args) {
Printer.print("Hello World!");
}

}

最佳答案

是的,这是可能的:

template <typename T>
void print(const std::string& text)
{
T::printText(text);
}

要确保 PrinterT 的基础,您可以将此编译时检查添加到函数中:

    static_assert(std::is_base_of<Printer, T>::value, "T must inherit from Printer");

关于java - 在 C++ 中的模板参数上调用静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39102254/

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