我正在嘗試撰寫這樣的模板函式
template<typename T>
T doSomething() {
//Code
if (std::is_same<T, int>::value) {
return getInt(); // A library function returning an int
} else if (std::is_same<T, bool>::value) {
return getBool(); // A library function returning a bool
} else {
throw;
}
}
根據給定的模板引數呼叫不同的函式并回傳一個值,該值在運行時保證與 T 具有相同的型別。但是,編譯器給了我這個錯誤:'return': cannot convert from 'int' to 'T'
我想我可以使用類似的東西reinterpret_cast,但這似乎在這種情況下是不安全和不好的做法。
那么,有沒有辦法根據 C 中的模板引數從模板函式回傳不同型別?
uj5u.com熱心網友回復:
那么,有沒有辦法根據 C 中的模板引數從模板函式回傳不同型別?
是的,您可以使用 C 17constexpr if
template<typename T>
T doSomething() {
//Code
if constexpr (std::is_same<T, int>::value) {
return getInt(); // A library function returning an int
} else if constexpr (std::is_same<T, bool>::value) {
return getBool(); // A library function returning a bool
} else {
throw;
}
}
uj5u.com熱心網友回復:
除了constexpr if(對于 c 17 之前的版本),您還可以使用顯式特化,如下所示:
template<typename T> //primary template
T doSomething() {
std::cout<<"throw version"<<std::endl;
throw;
}
template<> //specialization for int
int doSomething<int>() {
std::cout<<"int version"<<std::endl;
return getInt();
}
template<>//specialization for bool
bool doSomething<bool>() {
std::cout<<"bool version"<<std::endl;
return getBool();
}
演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/438907.html
