简体   繁体   English

模板 function 中的 void 参数

[英]void argument in template function

I try to create generic convert function.我尝试创建通用转换 function。 How to create template function than can have void argument?如何创建模板 function 比可以有 void 参数? Something like this:像这样的东西:

template<typename T1>
bool convert(T1 arg) {
    return true;
}

template<typename T1 = void>
bool convert(T1 arg) {
    return false;
}

void voidFn() {
    return;
}

bool boolFn() {
    return true;
}

void main() {
   cout << convert(boolFn());  //ok return true
   cout << convert(voidFn());  //compile error no matching function 
}

There's no such thing as a "void argument", in C or C++.在 C 或 C++ 中没有“无效参数”之类的东西。 This is done using ordinary overloading:这是使用普通重载完成的:

template<typename T1>
bool convert(T1 arg) {
    return true;
}

bool convert() {
    return false;
}

Also, depending on the actual details, there's a small chance that it might be possible to have a single template function that uses std::optional and user-defined deduction guides in C++17, and later.此外,根据实际细节,在 C++17 及更高版本中使用std::optional和用户定义的推导指南的单个模板 function 的可能性很小。

You can't have a void argument for a function. function 不能有void参数。

But you can have void type template parameter.但是你可以有void类型的模板参数。 So you need a function that select void /non void returning functions, you can try something as follows所以你需要一个 function 那个 select void /non void返回函数,你可以尝试如下

#include <iostream>

template <typename>
bool convert ()
 { return true; }

template <>
bool convert<void> ()
 { return false; }

void voidFn ()
 { return; }

bool boolFn ()
 { return true; }

int main ()
 {
   std::cout << convert<decltype(boolFn())>() << '\n'; // print 1
   std::cout << convert<decltype(voidFn())>() << '\n'; // print 0
 }

Obviously this can be useful only if it's relevant the type, not the exact value, returned from the functions.显然,只有当它与函数返回的类型而不是确切值相关时,这才有用。

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

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