c++ - 传递 constexpr 对象

标签 c++ c++14 constexpr

我决定尝试一下 constexpr 的新 C++14 定义,为了充分利用它,我决定编写一些编译时字符串解析器。但是,在将对象传递给函数时,我一直在努力保持对象为 constexpr。考虑以下代码:

#include <cstddef>
#include <stdexcept>

class str_const {
    const char * const p_;
    const std::size_t sz_;
public:
    template <std::size_t N>
    constexpr str_const( const char( & a )[ N ] )
    : p_( a ), sz_( N - 1 ) {}
    constexpr char operator[]( std::size_t n ) const {
        return n < sz_ ? p_[ n ] : throw std::out_of_range( "" );
    }
    constexpr std::size_t size() const { return sz_; }
};

constexpr long int numOpen( const str_const & str ){
    long int numOpen{ 0 };
    std::size_t idx{ 0 };
    while ( idx <  str.size() ){
        if ( str[ idx ] == '{' ){ ++numOpen; }
        else if ( str[ idx ] == '}' ){ --numOpen; }
        ++idx;
    }
    return numOpen;
}

constexpr bool check( const str_const & str ){
    constexpr auto nOpen = numOpen( str );
    // ...
    // Apply More Test functions here,
    // each returning a variable encoding the correctness of the input
    // ...

    return ( nOpen == 0 /* && ... Test the variables ... */ );
}

int main() {
    constexpr str_const s1{ "{ Foo : Bar } { Quooz : Baz }" };
    constexpr auto pass = check( s1 );
}

我使用 str_const classScott Schurr at C++Now 2012 呈现在针对 C++14 修改的版本中。

以上代码将无法编译并出现错误(clang-3.5)

error: constexpr variable 'nOpen' must be initialized by a constant expression  
    constexpr auto nOpen = numOpen( str );  
                           ~~~~~~~~~^~~~~

这让我得出结论,您不能在不丢失其 constexpr 特性的情况下传递 constexpr 对象。这让我想到了以下问题:

  1. 我的解释正确吗?

  2. 为什么这是标准规定的行为?

    我没有看到传递 constexpr 对象的问题。当然,我可以重写我的代码以适应单个函数,但这会导致代码拥挤。我认为将单独的功能分解为单独的代码单元(函数)也应该是编译时操作的好风格。

  3. 正如我之前所说,编译器错误可以通过将代码从单独的测试函数(例如 numOpen)移动到 顶层的主体来解决 函数检查。但是,我不喜欢这个解决方案,因为它创建了一个庞大而局促的功能。您是否看到了解决问题的不同方法?

最佳答案

原因是 constexpr 函数中,参数不是常量表达式,无论参数是否是。您可以在其他人内部调用 constexpr 函数,但是 constexpr 函数的参数不在 constexpr 内部,使得任何函数调用(甚至是 constexpr 函数)不是常量表达式 - inside

const auto nOpen = numOpen( str );

Suffices .只有当您从外部 查看调用时,才会验证内部表达式的constexpr 性,从而决定整个调用是否为constexpr

关于c++ - 传递 constexpr 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27291903/

相关文章:

c++ - 在 C++ 中赋予回调函数访问类数据成员的权限

c++ - 静态全局函数词汇

c++ - 将可变函数作为参数传递

c++ - 持有派生类引用的基类的 std::unique_ptr 在 gcc 编译器中不显示警告,而裸指针显示它。为什么?

c++ - 使用 constexpr 进行常量初始化

c++ - 为什么 putchar ('\\\' );不会工作

c++ - 智能指针与初始值设定项列表混淆

c++ - 是否有一种 STL 方法可以对指针 vector 进行深度复制?

c++ - g++ c++11 constexpr 评估性能

c++ - 最终二进制大小 : constexpr variable vs constexpr function