1

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

3 回答 3

2

不,但由于你总是返回一个指针,你可以只返回一个void*. 请注意,调用者将无法确定指针背后的内容,因此您最好尝试将返回值包装在boost::variant<char*,short*,int*>or boost::any/cdiggins::any

于 2013-10-06T11:07:02.993 回答
2

制作一个 getterbitsPerSample并让调用者选择适当的方法之一:

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 *
}
于 2013-10-06T11:09:03.857 回答
0

不直接,我建议使用类似的东西:

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*
}
于 2013-10-06T11:23:19.130 回答