有没有办法在C++函数体内定义返回类型
Is there way to define return type inside the body of function in C++?
如何在运行时在函数中定义返回类型?我有一个成员 char* m_data;我想在不同情况下将m_data转换为不同类型的内容返回。
?type? getData() const
{
switch(this->p_header->WAVE_F.bitsPerSample)
{
case 8:
{
// return type const char *
break;
}
case 16:
{
// return type const short *
break;
}
case 32:
{
// return type const int *
break;
}
}
}
不,但是由于您总是返回指针,因此您可以只返回一个void*
。请注意,调用者无法确定指针后面的内容,因此最好尝试将返回值包装在boost::variant<char*,short*,int*>
或boost::any
/cdiggins::any
为bitsPerSample
做一个getter,让调用者选择适当的方法之一:
int getBitsPerSample(){
return p_header->WAVE_F.bitsPerSample;
}
const char* getDataAsCharPtr() {
// return type const char *
}
const short* getDataAsShortPtr() {
// return type const short *
}
const int* getDataAsIntPtr() {
// return type const int *
}
不是直接的,我建议使用类似的东西:
const char* getDataAsChar() const
{
if (this->p_header->WAVE_F.bitsPerSample != 8) return nullptr;
//return data as const char*
}
const short* getDataAsShort() const
{
if (this->p_header->WAVE_F.bitsPerSample != 16) return nullptr;
//return data as const short*
}
const int* getDataAsInt() const
{
if (this->p_header->WAVE_F.bitsPerSample != 32) return nullptr;
//return data as const int*
}
相关文章:
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- QtQuick - qml:28:错误:未知方法返回类型:自定义类型
- 如何在C++中允许成员函数的自定义返回类型进行类型擦除?
- 如何在 Cython 中定义返回 cpp 定义类型的函数?
- 用户定义的转换无法指定返回类型
- 将成员函数的返回类型引用到C++中的自定义类
- 如何定义依赖于参数包转换的函数的返回类型
- 在类定义中推导内联静态成员函数的返回类型
- 如果函数是在类的主体中定义的,我是否需要在成员函数的返回类型中指定 typename?
- 从 QAbstractItemModel 返回自定义用户类型
- 为什么用户定义的转换函数模板不能有推导的返回类型?
- 重载运算符返回什么类型的值(对于用户定义的类型):右值还是左值?
- 在Cython中定义C 结构返回类型
- 为什么在.h中定义的私有结构需要.cpp文件中的返回类型中的范围
- 是否可以为类设置自定义返回类型
- 具有自定义返回类型和"false"返回条件的函数?
- 在派生类中定义自定义返回类型的受保护方法
- 有没有办法在C++函数体内定义返回类型
- 自定义返回类型声明
- 具有自定义返回类型的全局命名空间中的友元函数