gpt4 book ai didi

c++ - 根据类型返回值

转载 作者:太空狗 更新时间:2023-10-29 19:39:35 24 4
gpt4 key购买 nike

考虑下面的例子

template<class Type = void> class MyClass
{
public:
double getValue()
{
// if "Type == void" return _x, if "Type != void" return _y
return (/* SOMETHING */) ? (_x) : (_y);
}
protected:
double _x;
static const double _y;
};

/* SOMETHING */ 条件可能是什么?

如果模板参数为void,我想返回_x,否则返回_y。怎么做?

最佳答案

首先,你不能返回任何东西,因为函数返回类型是void(已修复)

其次,当 Typevoid 时,您可以专门化该函数以执行不同的操作:

template<class Type> class MyClass
{
public:
double getValue()
{
return _y;
}
protected:
double _x;
static const double _y;
};

template<>
inline double MyClass<void>::getValue()
{
return _x;
}

关于c++ - 根据类型返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12598221/

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