Home >Backend Development >C++ >Special usage of C++ function default parameters and variable parameters in template programming

Special usage of C++ function default parameters and variable parameters in template programming

WBOY
WBOYOriginal
2024-04-22 15:12:02644browse

Special usage of default parameters and variable parameters in template programming in C: Default parameters allow functions to use default values ​​when no parameters are specified, thereby realizing the genericization of function overloading. Variable parameters allow functions to receive any number of parameters, achieving code versatility and can be used for functions or generic containers that handle any number of parameters. Practical case: Implemented a general decimal formatting function, using default parameters to specify different precisions for different types of decimals.

C++ 函数默认参数和可变参数在模板编程中的特殊用法

Special usage of C function default parameters and variable parameters in template programming

In C template programming, the use of default parameters and variable parameters It can greatly enhance the efficiency and versatility of the code. Let's explore their special uses:

Default Parameters

Default parameters allow certain parameters to be omitted when calling a function. When parameters are not specified, default values ​​are used. For example:

template<typename T, typename U = T>
auto sum(T a, U b = 0) {
    return a + b;
}

In the above example, b is a default parameter with a default value of 0. We can call this function like this:

int total = sum(10); // b 默认值为 0,结果为 10

Variadic parameters

Variadic parameters allow a function to receive any number of arguments. They are represented using the ... operator. For example:

template<typename T>
auto print_all(T... args) {
    for (auto arg : {args...}) {
        std::cout << arg << ' ';
    }
    std::cout << '\n';
}

In this example, args is a variadic argument pack that can receive any number of T type arguments. We can call this function like this:

print_all(1, 2.5, "hello"); // 输出:"1 2.5 hello"

Special usage in template programming

  • Function overloading and genericization: Default parameters can generalize overloaded functions, eliminating the need for specific parameter dependencies. For example, we can provide different types of default separators in a generic print function:
template<typename T, typename D = char>
auto print_delimited(T value, D delimiter = ' ') {
    std::cout << value;
    if constexpr (std::is_same_v<D, char>) { // 如果分隔符为字符
        std::cout << delimiter;
    } else { // 如果分隔符为字符串
        std::cout << delimiter << '\n';
    }
}
  • Genericizing the number of arguments: Variadic arguments allow the function to handle any number parameters to achieve code versatility. For example, we can use variadic arguments in a sum function passing any number of arguments:
template<typename T>
auto sum_all(T... args) {
    return (... + args);
}
  • Container genericization: Default parameters and variadic parameters can Plays a key role in container genericization. For example, we can create a generic container whose element types can be deduced from the function call:
template<typename T, typename Alloc = std::allocator<T>>
class Vector {
public:
    Vector(T... args) {
        for (auto arg : {args...}) {
            emplace_back(arg);
        }
    }
};

Practical Case

Create a generic decimal format function, using default parameters to specify different precisions for different types of decimals:

template<typename T, typename D = T, D precision = 2>
std::string format_float(T value) {
    std::stringstream ss;
    ss << std::fixed << std::setprecision(precision) << value;
    return ss.str();
}

We can use this function in the following scenarios:

std::cout << format_float(3.14159265) << '\n'; // 输出:"3.14" (默认精度为 2)
std::cout << format_float<float>(3.14159265, 6) << '\n'; // 输出:"3.141593" (精度为 6)

The above is the detailed content of Special usage of C++ function default parameters and variable parameters in template programming. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn