小编Eoi*_*oin的帖子

具有非类型参数的成员函数的部分特化

我有一个带有类型和非类型模板参数的模板类.我想专门化一个成员函数,我发现的是,如下例所示,我可以完全专业化.

template<typename T, int R>
struct foo
{
    foo(const T& v) :
        value_(v)
    {}

    void bar()
    {
        std::cout << "Generic" << std::endl;
        for (int i = 0; i < R; ++i)
            std::cout << value_ << std::endl;
    }

    T value_;
};

template<>
void foo<float, 3>::bar()
{
    std::cout << "Float" << std::endl;
    for (int i = 0; i < 3; ++i)
        std::cout << value_ << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

但是这种部分特化不会编译.

template<int R>
void foo<double, R>::bar()
{
    std::cout << "Double" << std::endl;
    for (int i …
Run Code Online (Sandbox Code Playgroud)

c++ templates partial-specialization template-specialization

10
推荐指数
1
解决办法
7558
查看次数

如何使用最少的位生成任意范围内的无偏随机数

因为鸽子洞原理,不能随便用

output = min + (rand() % (int)(max - min + 1))
Run Code Online (Sandbox Code Playgroud)

生成无偏的、统一的结果。This answer to a similar question提供了一种解决方案,但就消耗的随机位而言,这是非常浪费的。

例如,如果源的随机范围很小,那么必须从源生成第二个值的机会可能会非常高。或者,使用更大的源范围本质上也是浪费。

虽然我确信可以推导出最佳的源范围大小,但这并没有解决可能存在更好算法的问题,而不是优化这个算法。

[编辑] 我的想法已在答案中显示,以产生有偏见的结果。

我想到的一种方法是

  1. 消耗覆盖所需范围所需的最少位数。
  2. 如果该值超出所需范围,则仅丢弃一位并再消耗一位。
  3. 根据需要重复。

random algorithm uniform

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

如何确定从Google Play游戏循环播放通知中选择的匹配项

当用户接收并点击基于回合的通知时,弹出默认UI,允许他们选择继续转向/邀请.然后启动我的游戏.

但是我无法弄清楚如何确定哪个转弯/邀请用户选择并自动加载相应的匹配.

目前,我被迫重新展示默认匹配的收件箱用户界面,并对其进行反应.

android google-play-games

3
推荐指数
1
解决办法
530
查看次数

模板化类的模板化成员的编译失败.VC++有效,但G ++失败了

以下代码在Visual C++ 2010下编译良好,但在Android NDK r8b下不在GCC 4.6下编译.

template<typename A>
struct foo
{
    template<typename B>
    B method()
    {
        return B();
    }
};

template<typename A>
struct bar
{
    bar()
    {
        f_.method<int>(); // error here
    }

private:
    foo<A> f_;
};
Run Code Online (Sandbox Code Playgroud)

GCC给出的错误是

error : expected primary-expression before 'int'
error : expected ';' before 'int'
Run Code Online (Sandbox Code Playgroud)

对于标记线.对于我的生活,我无法弄清楚什么是错的.

c++

2
推荐指数
1
解决办法
79
查看次数

使用基类指针的右值引用的函数具有来自复制的派生类的指针

这是我的意思的一个简短的例子.我发现很难简洁地说出这个问题.

struct A {};
struct B : public A {};

void foo(A*&& ap)
{
    ap = nullptr;
}

int main()
{
    B b;

    A* ap = &b;

    foo(std::move(ap));
    std::cout << (ap == nullptr ? "null" : "not null") << std::endl;

    B* bp = &b;

    foo(std::move(bp));
    std::cout << (bp == nullptr ? "null" : "not null") << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我希望这会打印出来

null
null
Run Code Online (Sandbox Code Playgroud)

而是它打印

null
not null
Run Code Online (Sandbox Code Playgroud)

快速查看x86反汇编会显示不需要的复制,仅适用于以下B*情况:

lea         eax,[bp]  
push        eax  
call        std::move<B * &> (03E14BFh)  
add         esp,4  
mov …
Run Code Online (Sandbox Code Playgroud)

c++ pointers rvalue-reference

0
推荐指数
1
解决办法
1431
查看次数