Vin*_*ent 3 c++ templates type-traits c++11
请考虑以下示例
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;
};
Run Code Online (Sandbox Code Playgroud)
可能是什么/* SOMETHING */条件?
我想_x在模板参数为void时返回,_y如果没有则返回.怎么做 ?
Luc*_*ore 12
首先,你不能返回任何东西,因为函数返回类型是(固定)void.
其次,你可以专注该功能时采取不同的行动Type是void:
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;
}
Run Code Online (Sandbox Code Playgroud)