小编euc*_*ian的帖子

如何使用隐式模板类型推导

我正在尝试编写一个模板来计算编译期间数字的功效(我不是模板元编程专家所以任何评论都表示赞赏).以下是代码:

template<typename T, T X, uint64_t P>
struct Pow
{
    static constexpr T result = X * Pow<T,X, P - 1>::result;
};
template<typename T, T X>
struct Pow<T, X, 0>
{
    static constexpr T result = 1;
};
template<typename T, T X>
struct Pow<T, X, 1>
{
    static constexpr T result = X;
};
Run Code Online (Sandbox Code Playgroud)

我需要称之为:

Pow<decltype(4), 4, 2>::result
Run Code Online (Sandbox Code Playgroud)

问题:有没有办法编写帮助模板,以便呼叫跳过decltype?例如:

Pow<4, 2>::result
Run Code Online (Sandbox Code Playgroud)

我已经阅读了以下内容,但到目前为止,我看不到答案(看起来恰恰相反),这个,这个,这个.

c++ templates decltype template-meta-programming

10
推荐指数
2
解决办法
552
查看次数

constexpr for 循环编译

我已经读过这篇文章,但我仍然不知道如何使其工作,-std=gnu++2a 我不知道如何使用integer seq。您能帮我修改下面的代码以便它可以编译吗?谢谢

constexpr bool example(const int k)
{
    return k < 23 ? true: false;
}

constexpr bool looper()
{
    constexpr bool result = false;
    for(int k = 0; k < 20; k ++)
    {
        for (int i = 0 ; i < k; ++i)
        {
        constexpr bool result = example(i);
        }
    }

    return result;
}

int main()
{
    constexpr bool result = looper();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ metaprogramming constexpr c++11 c++17

5
推荐指数
1
解决办法
3398
查看次数

编译时循环优化

我发现很难理解为什么以下结果会导致编译时计算。我已经阅读了thisthisthis和更多关于stackoverflow的问题,这些问题告诉我以下代码(至少据我所知)由于while循环而不应在编译时计算(该代码仅是示例说明了题):

template< unsigned N >
constexpr unsigned isStringNice(const char (&arr)[N], unsigned pos = 0)
{
    //we do not like the 'D' char :)
    int currPos = 0;
    while(currPos < N){
        if(arr [currPos] == 'D'){
            throw 1;
        }
        currPos ++;
    }
    return 1;
}
constexpr unsigned isIdxValid( unsigned idx, unsigned len){
    return idx >= len?  throw 1 : idx;
}

template< unsigned N >
constexpr char nth_char(const char (&arr)[N], unsigned pos){
  return  isStringNice(arr),isIdxValid(pos, …
Run Code Online (Sandbox Code Playgroud)

c++ gcc constexpr c++11 c++17

4
推荐指数
1
解决办法
1218
查看次数

我可以将枚举类型从字符串更改为字节吗?

我试图通过套接字发送一个枚举值,但是无论我尝试什么,它都会被编码为字符串(除非我在对 socket.send 的调用中手动将其转换为字节)

class Example(Enum):
    A = b'example'
    B = bytes('example', 'utf8')
Run Code Online (Sandbox Code Playgroud)

我从套接字模块调用 send 方法,其中 sock 是服务器的先前绑定套接字

....
conn, addr = sock.accept() 
conn.send(Example.A.name)
Run Code Online (Sandbox Code Playgroud)

异常消息是:

a bytes-like object is required, not 'str'
Run Code Online (Sandbox Code Playgroud)

我已经阅读了这个和其他一些链接,但我找不到答案。

python enums python-3.x

4
推荐指数
1
解决办法
243
查看次数