代码之家  ›  专栏  ›  技术社区  ›  Jan021981

具有可选参数或重载的函数模板

  •  0
  • Jan021981  · 技术社区  · 7 年前

    我得到了一个类,在一个经典的C数组中包含20个结构元素。从0到5的元素属于A型,从6到15的元素属于B型,其余的元素属于C型。 为了循环这些元素,我设计了三个函数模板。这是我的问题的一个非常简单的例子(我知道,这毫无意义,但它只说明了我想要什么):

    #include <iostream>
    #include <string>
    
    struct MyStruct {
        int Value;
    
    MyStruct() {
        this->Value = 0;
    }
    
    MyStruct(int fValue) {
        this->Value = fValue;
    }
    
    void PrintValue() { std::cout << "Value: " << std::to_string(this->Value) << std::endl; }
    };
    
    class MyClass {
    private:
        struct MyStruct valArr[20];
        int aRange = 5;
        int bRange = 10;
    
    public:
        MyClass() {
            for (int i = 0; i < 20; i++) {
                valArr[i] = MyStruct(i);
            }
    }
    
    template<typename FUNCTION>
    inline void LoopRangeA(FUNCTION f, bool GetIndex = false) {
            for (int i = 0; i < aRange; i++) {
                f(&this->valArr[i]);
            }
    }
    
    template<typename FUNCTION>
    inline void LoopRangeB(FUNCTION f) {
        for (int i = aRange; i < bRange; i++) {
            f(&this->valArr[i]);
        }
    }
    
    template<typename FUNCTION>
    inline void LoopRangeC(FUNCTION f) {
        for (int i = bRange; i < 20; i++) {
            f(&this->valArr[i]);
        }
    }
    
    template<typename FUNCTION>
    inline void LoopAll(FUNCTION f) {
        for (int i = 0; i < 20; i++) {
            f(&this->valArr[i]);
        }
    }
    };
    
    int main() {
    MyClass Cls = MyClass();
    
    Cls.LoopRangeA([](MyStruct* pStr) {pStr->PrintValue(); });
    
        std::cout << "Application is finished. Press ENTER to exit..." << std::endl;
    std::cin.get();
    }
    

    嗯,这很好。但有时,我还需要元素的数组索引。由于我的实际程序中仍然有很多这个函数模板,我尽量避免定义新函数,但希望重载它们或使用可选参数。

        template<typename FUNCTION>
    inline void LoopRangeA(FUNCTION f, bool GetIndex = false) {
        if (GetIndex) {
            for (int i = 0; i < aRange; i++) {
                f(&this->valArr[i], i);
            }
        }else {
            for (int i = 0; i < aRange; i++) {
                f(&this->valArr[i]);
            }
        }
    }
    
    int main() {
        MyClass Cls = MyClass();
    
        Cls.LoopRangeA([](MyStruct* pStr, int& i) {std::cout << "Index: " << std::to_string(i); pStr->PrintValue(); std::cout << "" << std::endl; }, true);
        std::cout << "Application is finished. Press ENTER to exit..." << std::endl;
        std::cin.get();
    }
    

    提前感谢您, 简

    3 回复  |  直到 7 年前
        1
  •  0
  •   Ravinder Singh    7 年前

    如果您可以使用constexpr,那么在constexpr中,如果代码在编译时进行了优化,这意味着如果传递false,编译器将直接编译,否则,如果这意味着不会产生错误,编译器将不进行编译。

     if constexpr (GETINDEX){
        //do something f(par1,par2);
     }
     else{
       //or f(par1);
     }
    

    现在,当u编译这个,GETINDEX为false时,f(par1,par2)将不会被检查,否则将被编译。这将帮助您调用函数。

        2
  •  0
  •   TrebledJ    7 年前

    In instantiation of 'void MyClass::LoopRangeA(FUNCTION, bool) [with FUNCTION = main()::<lambda(MyStruct*, int)>]':
    46:14: error: no match for call to '(main()::<lambda(MyStruct*, int)>) (MyStruct*)'
                 f(&this->valArr[i]);
                 ~^~~~~~~~~~~~~~~~~~
    

    所以我怀疑这与你的 else 案例:

    template<typename FUNCTION>
    inline void LoopRangeA(FUNCTION f, bool GetIndex = false) {
        if (GetIndex) {
            for (int i = 0; i < aRange; i++) {
                f(&this->valArr[i], i);
            }
        }else {
            for (int i = 0; i < aRange; i++) {
                f(&this->valArr[i]);            //   <-- this guy over here
            }
        }
    }
    

    错误输出提供的重要信息是:

    FUNCTION = main()::<lambda(MyStruct*, int)>
    

    全部的 调用和实例,无论是否执行它们。为lambda提供默认参数修复了它:

    [&](MyStruct* pStr, int i = -1) {...}
    

    else {
        for (int i = 0; i < aRange; i++) {
            f(&this->valArr[i], -1);       //  -1
        }
    }
    

    之后代码运行良好。

    但是使用 -1 可能有点太粗糙(“魔术数字”等等),所以我可能会选择 std::optional 相反

        3
  •  0
  •   florestan    7 年前

    我看到了三种可能的解决方案,但可能还有更多:

    1) 过载 LoopRangeA 对于这两种类型的函数:

    inline void LoopRangeA(void (*f)(MyStruct*)) {
        for (int i = 0; i < aRange; i++) {
            f(&this->valArr[i]);
        }
    }
    
    inline void LoopRangeA(void (*f)(MyStruct*, size_t)) {
        for (int i = 0; i < aRange; i++) {
            f(&this->valArr[i], i);
        }
    }
    

    这将根据函数签名选择循环的类型。缺点是,您可能需要为 onst Mystruct*

    2) 如果你可以使用C++17,你可以利用 if constexpr 通过提供 bool

    template<bool GetIndex, typename FUNCTION>
    void LoopRangeA1(FUNCTION f) {
        if constexpr(GetIndex) {
            for (int i = 0; i < aRange; i++) {
                f(&this->valArr[i], i);
            }
        } else {
            for (int i = 0; i < aRange; i++) {
                f(&this->valArr[i]);
            }
        }
    }
    

    但是,正如@StoryTeller在其评论中提到的那样,您必须传递冗余信息,因为索引的需要无论如何都是在函数签名中编码的。

    3) 因此,我更倾向于第三种解决方案,它充分利用了其他两种解决方案:

    首先,您提供了一个函数,该函数确定在编译时读取索引的能力。这需要一些小技巧:

    constexpr std::false_type eats_index(...) { return {}; }
    
    template<typename T>
    constexpr auto eats_index(T) -> decltype(std::declval<T>()(std::declval<MyStruct*>(), 0), std::true_type{}) {
        return {};
    }
    

    然后您可以这样实现您的功能:

    template<typename FUNCTION>
    void LoopRangeA2(FUNCTION f) {
        if constexpr(eats_index(f)) {
            for (int i = 0; i < aRange; i++) {
                f(&this->valArr[i], i);
            }
        } else {
            for (int i = 0; i < aRange; i++) {
                f(&this->valArr[i]);
            }
        }
    }
    

    main 显示如何使用解决方案的函数:

    int main() {
        MyClass Cls = MyClass();
    
        auto print_no_idx = [](MyStruct* pStr) {pStr->PrintValue(); };
        auto print_const_no_idx = [](const MyStruct* pStr) { };
        auto print_with_idx = [](MyStruct* pStr, size_t idx) {
            std::cout << "index: " << idx << " -> ";
            pStr->PrintValue();  };
    
        Cls.LoopRangeA(print_no_idx);
        Cls.LoopRangeA(print_const_no_idx); // <- does not compile, you'd need another overload
        Cls.LoopRangeA(print_with_idx);
    
        Cls.LoopRangeA1<false>(print_no_idx);
        Cls.LoopRangeA1<false>(print_const_no_idx); // <- works w/o additional overload
        Cls.LoopRangeA1<true>(print_with_idx);
    
        static_assert(!eats_index(print_no_idx));
        static_assert(eats_index(print_with_idx));
    
        Cls.LoopRangeA2(print_no_idx);
        Cls.LoopRangeA2(print_const_no_idx); // <- works, w/o additional overload
        Cls.LoopRangeA2(print_with_idx);
    
    
    
    
        std::cout << "Application is finished. Press ENTER to exit..." << std::endl;
        std::cin.get();
    }
    

    here