No, but as you always return a pointer you could just return a void*
. Beware the caller would have no option to figure out what is behind the pointer, so you better try to wrap the return value in boost::variant<char*,short*,int*>
or boost::any
/cdiggins::any
Is there way to define return type inside the body of function in C++?
-
30-06-2022 - |
Question
How i can define return type inside function at run-time? I have a member char* m_data; and I want to return a conversion of m_data into different types in different cases.
?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;
}
}
}
Solution
OTHER TIPS
Make a getter for bitsPerSample
and let the caller choose one of the appropriate methods:
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 *
}
Not directly, I suggest to use something like :
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*
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow