[根据更新要求更新问题]
我已经实现了以下函数,它应该返回第一个非空元素或抛出异常。
您还可以发明更经典和更短的名称,例如“max”、“min”、“pair”吗?
template <typename T>
T select_first_not_empty( const T& a, const T&b )
{
static T null = T();
if ( a == null && b == null )
throw std::runtime_error( "null" );
return
a != null ? a : b;
}
int main()
{
const int a1 = 2;
const int b1 = 0;
const int* a2 = 0;
const int* b2 = new int(5);
const std::string a3 = "";
const std::string b3 = "";
std::cout << select_first_not_empty( a1, b1 ) << std::endl;
std::cout << select_first_not_empty( a2, b2 ) << std::endl;
std::cout << select_first_not_empty( a3, b3 ) << std::endl;
return 0;
}