【问题标题】:Is it possible to have a branch of code conditionally be compiled in C++?是否可以有条件地在 C++ 中编译代码分支?
【发布时间】:2015-02-24 16:08:56
【问题描述】:

标题确实说明了一切。说明事务精神的示例代码:

if( std::is_constructible<T, unsigned long>::value )
{
    unsigned long identity = collection.rbegin()->first + 1;
    std::shared_ptr<T> newObject(new T(identity));

    collection.insert( identity , newObject );
    return true;
}
else
{
    return false;
}

【问题讨论】:

  • D 语言将此作为静态 if,而 DM C++ 将此作为扩展。但它不是标准 C++ 的一部分。
  • 优化器会移除无用的分支......
  • 是的,但不是那种语法。搜索“标签调度”。

标签: c++11 metaprogramming boost-mpl


【解决方案1】:

标签调度。

template<class T>
bool foo_impl(std::true_type){
    unsigned long identity = collection.rbegin()->first + 1;
    std::shared_ptr<T> newObject(new T(identity));
    collection.insert( identity , newObject );
    return true;
}

template<class T>
bool foo_impl(std::false_type){
    return false;
}

template<class T>
bool foo(){
    return foo_impl<T>(std::is_constructible<T, unsigned long>());
}

【讨论】:

    【解决方案2】:

    由于if 语句可以在编译时确定,我希望编译器能够智能并直接对其进行优化,就像你有类似的东西一样

    if ( true ) {
        // Some code
    }
    else {
        // Anything here any decent compiler will ignore.
    }
    

    另一种选择是将您想要的行为包装在一个函数中,并使用std::enable_if:

    template <typename T, typename = typename enable_if<is_constructible<T, int>::value>::type>
    bool foo() {
        return true;   
    }
    
    template <typename T, typename = typename enable_if<!is_constructible<T, int>::value>::type>
    bool foo() {
        return false;
    }
    
    // ...
    
    return foo<T>();
    

    示例:http://ideone.com/sgNVr5

    另一种选择是专门处理布尔值:

    template <bool b> bool foo();
    
    template <>
    bool foo<true>(){
        return true;
    }
    
    template <>
    bool foo<false>() {
        return false;
    }
    

    【讨论】:

    • 如果你的一个分支在条件为假的情况下无法编译,那将无济于事,我想作者正在理解这一点。当然,优化编译器应该能够像这样进行微不足道的分支消除。
    • 是的,这更多是关于语法糖而不是关于死代码剥离。在编译时为 false 的分支也会在编译时中断构建。标签调度似乎是我想要的。
    • @MB。我提出的两个模板选项不应破坏您的构建,因为编译器只会实例化在编译时选择的分支,而忽略另一个。例如,这正是 std::enable_if 的用例。
    猜你喜欢
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 2012-03-14
    • 2010-11-29
    • 1970-01-01
    相关资源
    最近更新 更多