c++ 03检查模板参数是否为空

C++03 check if template parameter is void?

本文关键字:是否 参数 检查 c++      更新时间:2023-10-16

考虑一个函数

template <typename Ret>
Ret function(...) {
    Ret a;
    // . . . do something with a
    return a;
}

如果我把它命名为

function<void>();

编译器说

错误:变量或字段'a'声明为空

错误:return语句带值,函数返回'void' [-fpermissive]

如何在这个函数中强制检查,例如

template <typename Ret>
Ret function(...) {
    // if (Ret is void) return;
    Ret a;
    // . . . do something with a
    return a;
}

我知道c++ 11有std::is_voidstd::is_same

bool same = std::is_same<Ret, void>::value;

c++ 03里有什么吗?

您可以专门化,或者编写自己的is_same,这很容易,当然您也可以使用非标准库(例如boost)。

专业化

template<typename Ret>
Ret function(...)
{
   Ret a;
   // ...
   return a;
}
template<>
void function<void>(...)
{
}

template<typename T, typename U>
struct is_same
{
   static const bool value = false;
};
template<typename T>
struct is_same<T, T>
{
   static const bool value = true;
};

顺便说一句,is_same并不像你想的那么简单。您还需要专门化或重载

template<typename Ret>
typename enable_if<!is_same<Ret, void>::value, Ret>::type
function(...)
{
   Ret a;
   // ...
   return a;
}
template<typename Ret>
typename enable_if<is_same<Ret, void>::value, Ret>::type
function(...)
{
}

运行时if是不够的,模板的所有实例化必须是可编译的。在你的情况下,专业化可能是最好的做法:

template <typename Ret>
Ret function(...) {
    Ret a;
    // . . . do something with a
    return a;
}
template <>
void function<void>(...) {
    return;
}

同时,boost::is_same可用于c++ 03。

相关文章: