简体   繁体   English

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

[英]C++03 check if template parameter is void?

Consider a function 考虑一个功能

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

If I call this as 如果我这样称呼

function<void>();

the compiler says 编译器说

error: variable or field 'a' declared void 错误:变量或字段“ a”声明为无效

error: return-statement with a value, in function returning 'void' [-fpermissive] 错误:函数中返回值“ void”的返回语句[-fpermissive]

How do I enforce a check on in this function, for instance 例如,如何在此功能中强制执行检查

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

I know C++11 has std::is_void and std::is_same 我知道C ++ 11有std::is_voidstd::is_same

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

Anything in C++03 ? C ++ 03中有什么吗? Thanks in advance. 提前致谢。

You can just specialize, or write your own is_same , that's pretty easy, or of course you can use not-standard libraries (for example boost). 您可以专门化或编写自己的is_same ,这非常简单,或者当然可以使用非标准的库(例如boost)。

Specialization 专业化

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

template<>
void function<void>(...)
{
}

Own 拥有

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;
};

BTW with is_same it's not so simple, that you think. 顺便说一句,使用is_same并不是那么简单,您认为。 You also need specialization, or overloading 您还需要专门化或超载

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(...)
{
}

So, just specialization is more simple. 因此,仅专业化就更简单。

A runtime if would not be enough, all instantiations of a template must be compilable. 运行时if是不够的,模板的所有实例必须是编译。 In your case, a specialisation might be the best course of action: 在您的情况下,专业化可能是最好的做法:

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

template <>
void function<void>(...) {
    return;
}

Also, there is boost::is_same available for C++03. 此外,C ++ 03 boost::is_same提供了boost::is_same

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM