C++ 选择第一个非空元素

标签 c++ naming std


[问题根据更新要求更新]
我已经实现了以下函数,它应该首先返回非空元素或抛出异常。
您还能发明更经典、更短的名称,例如“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;
}

最佳答案

你可以尝试下一步

template < typename T >
T get_valuable( const T& firstValue, 
                const T& alternateValue, 
                const T& zerroValue = T() )
{
    return firstValue != zerroValue ? firstValue : alternateValue;
}

// usage
char *str = "Something"; // sometimes can be NULL
std::string str2 ( get_valuable( str,  "" ) );

// your function
template <typename T>
T select_first_not_empty( const T& a, 
                          const T& b, 
                          const T& zerroValue = T() )
{
    const T result = get_valuable( a, b, zerroValue );
    if ( result == zerroValue )
    {
        throw std::runtime_error( "null" );
    }
    return result;
}

关于C++ 选择第一个非空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/631770/

相关文章:

c++ - 模板参数推导失败

c++ - 如何消除挑战 'Sam and sub-strings' 中与模数相关的错误?

c# - C#中变量名中@字符的用途/含义是什么?

c++ - 如何访问 vector 值 std::vector <cv::Point2f> pto

c++ - std::vector.push_back() C++

c++ - 具有非静态成员函数的 std::function

c++ - 在 C++11 中定义 lambda 函数不会在类内部编译

javascript - setTimeout 执行的函数叫什么?

xcode - 在Xcode中复制目标时,是否有任何方法可以设置目标在创建之前或创建时将拥有的名称?

c++ - 缺少 unique_ptr 和 friend operator= overload