簡體   English   中英

使用二進制搜索進行模板遞歸

[英]Template recursion using binary search

考慮一下我編寫的以下工作代碼:

#include <iostream>

constexpr int MIN_FOO = 0,  MAX_FOO = 100;

template <int N>
void foo() {std::cout << "foo<" << N << ">() called.\n";}

template <int N>
void foo (char, double, bool) {std::cout << "foo<" << N << ">(char, double, bool) called.\n";}


template <int Low, int High, typename... Args>
void searchFooBinary (int key, Args... args) {
//  if (LOW > HIGH) {std::cout << "Error with searchFooBinary.\n";  return;}
    constexpr int Mid = (Low + High) /2;
    if (key == Mid)
        foo<Mid>(std::forward<Args>(args)...);  // Want to generalize this using 'f'.
    else if (key < Mid)
        searchFooBinary<Low, Mid - 1>(key, std::forward<Args>(args)...);
    else
        searchFooBinary<Mid + 1, High>(key, std::forward<Args>(args)...);
}

template <typename... Args>
void executeFooBinarySearch (int n, Args... args) {
    searchFooBinary<MIN_FOO, MAX_FOO>(n, std::forward<Args>(args)...);
}

int main() {
    executeFooBinarySearch(99);
    executeFooBinarySearch (99, 'a', 1.5, true);
}

因此foo是模板函數,在這里傳遞了運行時int,而searchFooBinary使用二進制搜索來找到template參數的正確int值。 到目前為止,一切都很好,但是我不想為每個新函數(如foo編寫此二進制搜索函數。 如何將在searchFooBinary使用foo推廣到更通用的f 如果不允許使用模板函數指針,那么實現此目標的解決方法是什么?

如何使用函子:

#include <iostream>

constexpr int MIN_FOO = 0,  MAX_FOO = 100;

struct Foo
{
    template <int N>
    void operator() (char, double, bool) {std::cout << "Foo<" << N << ">(char, double, bool) called.\n";}
};

struct Bar
{
    template <int N>
    void operator() () {std::cout << "Bar<" << N << ">() called.\n";}   
};


template <int Low, int High, typename Fun, typename... Args>
void searchBinary (int key, Fun f, Args... args)
{
    constexpr int Mid = (Low + High) /2;
    if (key == Mid)
    {
        f.template operator()<Mid>(std::forward<Args>(args)...);
    }
    else if (key < Mid)
    {
        searchBinary<Low, Mid - 1>(key, f, std::forward<Args>(args)...);
    }
    else
    {
        searchBinary<Mid + 1, High>(key, f, std::forward<Args>(args)...);
    }
}

template <typename Fun, typename... Args>
void executeBinarySearch (int n, Fun f, Args... args)
{
    searchBinary<MIN_FOO, MAX_FOO, Fun>(n, f, std::forward<Args>(args)...);
}

int main()
{
    executeBinarySearch (99, Foo(), 'a', 1.5, true);
    executeBinarySearch (99, Bar());    
}

輸出

Foo<99>(char, double, bool) called.
Bar<99>() called.

實時示例: http//ideone.com/fSoG5B

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM