我有以下代码...
#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在两个功能模板之间进行选择。 Live Example :
#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;
}
关于C++ 在模板声明中使用默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23169520/