[英]C++ using default values in template declaration
我有以下代码...
#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;
}
您可以创建一个无效类型(无),并使用特征类型指定返回类型:
#include <iostream>
struct None {};
// It may not be reasonable o provide the operator:
inline std::ostream& operator << (std::ostream& stream, None) {
return stream;
}
template<typename R>
struct Traits {
typedef R return_type;
};
template<>
struct Traits<void> {
typedef None return_type;
};
template<typename R>
typename Traits<R>::return_type X() { return typename Traits<R>::return_type(); }
template<typename R, typename Traits<R>::return_type V>
typename Traits<R>::return_type X() { return V; }
int main()
{
std::cout << std::boolalpha << X<bool>() << std::endl;
std::cout << std::boolalpha << X<bool, true>() << std::endl;
std::cout << X<int>() << std::endl;
std::cout << X<int, 5>() << std::endl;
std::cout << X<void>() << std::endl;
return 0;
}
此外,函数X
分为两个,以避免默认模板参数出现问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.