C++安全的窄转换narrow_cast的新语法实现

//利用了C++新语法:构造自动推导模板类型

template::value>>
    struct narrow_cast
{
    SOURCE source;
    narrow_cast(SOURCE s) : source(s){}
    
    template::value>>
        operator TARGET()
    {
        auto target = static_cast(source);
        if (static_cast(target) != source)
        {
            throw std::runtime_error("narrow_cast failed from " + to_string(source));
        }
        return target;        
    }

};

int main(int argc, char *argv[])
{
    int i  = 1;
    long long int j = 1ll << 34;
    i = narrow_cast(j);
    cout << i;
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

你可能感兴趣的:(C/C++)