[英]define a function to return specified type of std::variant 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*
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.