Refactoring with C++ 11

前端 未结 11 2388
夕颜
夕颜 2020-11-28 18:17

Given the new toolset provided by c++ lots of programmers, aiming at code simplification, expressiveness, efficiency, skim through their old code and make tweaks (some point

11条回答
  •  生来不讨喜
    2020-11-28 18:50

    Optimize simple mathematical functions with constexpr, especially if they are called inside inner loops. This would allow the compiler to calculate them at compilation saving you time

    Example

    constexpr int fibonacci(int i) {
        return i==0 ? 0 : (i==1 ? 1 : fibonacci(i-1) + fibonacci(i-2));
    }
    

    Another example is to use std::enable_if to limit the allowed template parameters types in a particular template function/class. This would make your code safer (in case you haven't use SFINAE to constrains the possible template arguments in your old code) when you implicit assume some property about the template types and it is just one extra line of code

    example:

    template
    <
       typename T, 
       std::enable_if< std::is_abstract::value == false, bool>::type = false // extra line
    >
    void f(T t) 
    { 
     // do something that depends on the fact that std::is_abstract::value == false
    }
    

    Update 1: If you have a small array where the size is known at compile time and you you want to avoid the overhead of the heap allocation in std::vector (meaning: you want the array on the stack), you only choice in C++03 was to use c-style arrays. Change that to std::array. It is a simple change that provides you a lot of the functionally present in std::vector + stack allocation (much faster than heap allocation as I said before).

提交回复
热议问题