我有以下代码...
#include <iostream>
using namespace std;
template<typename R, R V = R()> R X() { return V; }
int main()
{
cout << boolalpha << X<bool>() << endl;
cout << boolalpha << X<bool, true>() << endl;
cout << X<int>() << endl;
cout << X<int, 5>() << endl;
cout << X<void>() << endl; // compiler error
return 0;
}
...适用于bool和int情况,但不适用于void情况。有办法解决吗?
我知道这样的代码是可以接受的...
void F()
{
return void();
}
...因此需要以某种方式使该行为脱离模板。
使用std :: enable_if在两个功能模板之间进行选择。现场示例:
#include <iostream>
#include <type_traits>
using namespace std;
template<typename R, R V = R()>
typename std::enable_if<!is_same<R, void>::value, R>::type X() { return V; }
template<typename R>
typename std::enable_if<is_same<R, void>::value, R>::type X() { return; }
int main()
{
cout << boolalpha << X<bool>() << endl;
cout << boolalpha << X<bool, true>() << endl;
cout << X<int>() << endl;
cout << X<int, 5>() << endl;
X<void>(); // You can't print `void` with standard iostreams...
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句