gpt4 book ai didi

c++ - 我可以在模板中将一种类型作为默认值还是在 C++ 中为 null

转载 作者:行者123 更新时间:2023-11-28 06:18:07 25 4
gpt4 key购买 nike

我想开发这样一个类:

template <typename T>
class A
{
public void DoSomething()
{
if(T !=null)
{
// do some work
T.report("I am here");
// do some more work.
}
}
}

并像这样使用它:

 class B
{
public:
void report(std::string msg)
{
std::cout<<msg<<std::endl;
}
}

main()
{
A<B> reportToStd;
a<null> donotreport;
}

如此有效,如果我没有定义要报告的类,对象就不会报告回来。我的想法是让它变快,因为我可以将参数传递给 aach 对象,说明是否报告。我也不想有一个空的类,因为这很乱。

最佳答案

最好的方法是显式实例化模板类。像这样:

template<> class A<null_t>
{
void DoSomething() { }
};

这样,当使用该模板创建类时,它不会执行任何操作。

关于c++ - 我可以在模板中将一种类型作为默认值还是在 C++ 中为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29851477/

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