有没有办法在C++函数体内定义返回类型

Is there way to define return type inside the body of function in C++?

本文关键字:定义 返回类型 函数体 C++ 有没有      更新时间:2023-10-16

如何在运行时在函数中定义返回类型?我有一个成员 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*
}