避免基于作为模板参数的函数的返回值进行分支

2024-03-11

假设以下策略类负责算法的一个方面:

struct VoidF {
    static void f() {
        ... // some code that has side effects
    }
};

struct BoolF {
    static bool f() {
        bool res = ...; // some computation
        return res;
    }
};

The BoolF策略是“增强感知”:当 BoolF::f() 返回时true,算法可以退出。VoidF是“增强不知道”,因此它返回void(我不想强迫我的图书馆的用户返回bool当这对他来说没有任何意义时)。

目前算法是这样写的:

template <typename F>
struct Algorithm {
    void run() {
        ... // some computation here

        if (std::is_same<decltype(F::f()), bool>::value) {
            if (F::f()) return;
        } else
            F::f(); // If F is VoidF, there should be no branching and some
                    // compiler optimizations will be enabled

        ... // more computation, unless F::f() got rid of it
    }
};

当然,如果Algorithm实例化为VoidF。有没有办法以不应该有分支的方式解决这个问题Algorithm<VoidF>::run()如评论所示?


这是我自己在没有 SFINAE 的情况下所做的尝试:

template <typename F>
struct Algorithm {
    void run() {
        ... // some computation here

        myRun(std::integral_constant<
              bool, std::is_same<decltype(F::f()), bool>::value>());
    }

private:
    void myRun(std::true_type) {
        if (F::f()) return;
        moreComputation();
    }

    void myRun(std::false_type) {
        F::f();
        moreComputation();
    }

    void moreComputation() { ... }
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

避免基于作为模板参数的函数的返回值进行分支 的相关文章

随机推荐