[英]A function parameter of type void
是否可以在不定義GetValue<void>
的顯式特化的情況下編譯以下偽代碼?
template <class Increment = void>
inline int GetValue(const Increment & inc = {})
{
if constexpr (std::is_same_v<Increment, void>)
{
return 25;
}
else
{
return 25 + inc;
}
}
int main()
{
std::cout << GetValue(1) << std::endl; //compiles
std::cout << GetValue() << std::endl; //does not compile
}
在這個偽代碼中,我將一個值作為 GetValue 參數傳遞給我增加 25 個常量的值或某個指示“絕對沒有”的值。 如果void
類型的參數不能編譯,那么這個“絕對沒有”是什么以及如何表示它還不夠清楚。
如果我定義一個假類型
struct Nothing {};
它可能看起來什么都沒有,但不像“絕對沒有”。
不可以。您不能擁有void
類型的對象。 但是,您不需要專業化。 你所需要的只是一個重載:
int GetValue()
{
return 25;
}
template <class Increment>
int GetValue(const Increment& inc)
{
return GetValue() + inc;
}
您的另一個選擇是將模板參數默認為void
以外的其他值:
template <class Increment = int>
int GetValue(const Increment& inc = {})
{
return 25 + inc;
}
然后GetValue()
調用實際上變成了GetValue(0)
,它也完成了這項工作。
這是一個基於可變參數模板的想法:
template <typename ...INCREMENT>
int GetValue(const INCREMENT &...inc) {
// this "if" is not actually needed for this example, but if you want
// to discriminate between zero/non-zero number of parameters,
// it can be done this way
if constexpr (sizeof...(inc) == 0) {
return 25;
} else {
return (25 + ... + inc);
// or you can use this:
// const auto &i = (inc, ...);
// return 25 + i;
}
}
int main() {
std::cout<<GetValue(1)<<"\n";
std::cout<<GetValue()<<"\n";
}
請注意,此解決方案允許使用任意數量的參數。 如果你必須有一個零或一個參數GetValue
,我認為你可以使用 SFINAE 只允許一個參數。
(例如,您可以使用std::enable_if_t<sizeof...(INCREMENT)<=1, int>
作為函數的返回類型)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.