default template argument VS. default function argument

80 Views Asked by At
  • [Q0] The main question is: what is the difference between default template argument and default function argument as they allow us to do the same things?
  • [Q1] Does should I prefer default template argument when work just with compile time variables, because as it was described here it will always provide me a compile time evaluation?

I have some code to provide you examples. [FULL CODE]

  • [E1] Struct/Class case
template <typename val_ty, int t_size = 50>
struct buffer_a {
    using value_type = val_ty;


    buffer_a() : space(value_type{}, t_size) {}

    constexpr int size() const { return t_size; }


    std::vector<value_type> space;
};
template <typename val_ty>
struct buffer_b {
    using value_type = val_ty;


    buffer_b (int t_size = 50) : space(t_size, value_type{}) {}

    constexpr int size() const { return space.size(); }


    std::vector<value_type> space;
};
    // [CASE 1]: compile time buffer size
    buffer_a<double> buff_a;
    buffer_b<double> buff_b;

    coutn(buff_a.size()); // ---> 50
    coutn(buff_b.size()); // ---> 50


    // [CASE 2]: run time buffer size
    int run_time_size = 0; std::cin >> run_time_size;

    // buffer_a<int, run_time_size> buff_aa;
    //               ^~~~~~~~~~~~~
    // ERROR: non-type template argument is not a constant expression
    buffer_b<int> buff_bb(run_time_size);

    // cout(buff_aa.size());
    coutn(buff_bb.size()); // ---> $(run_time_size)
  • [E2] Function case
// [F1]
template <typename val_ty, int t_size = 50>
std::vector<val_ty> release_vector_a() {
    std::cout << "A: vector has been created\n";
    return std::vector<val_ty>(t_size, val_ty{});
}

// [F2]
template <typename val_ty>
std::vector<val_ty> release_vector_b (int size = 100) {
    std::cout << "B: vector has been created\n";
    return std::vector<val_ty>(size, val_ty{});
}

// [F3]
template <int t_size = 50>
std::vector<int> release_int_vector_a() {
    std::cout << "A<int>: vector has been created\n";
    return std::vector<int>(t_size);
}

// [F4]
std::vector<int> release_int_vector_b (int size = 100) {
    std::cout << "B<int>: vector has been created\n";
    return std::vector<int>(size);
}
    // [CASE 3]: related to [CASE 1]
    release_vector_a<int>(); // compile time evaluation, because template<>, does it?
    release_vector_b<int>(); // compile time evaluation, because template<>, does it?


    // [CASE 4]
    release_int_vector_a(); // compile time evaluation, because template<>!
    release_int_vector_b(); // no compile time evaluation, no template<> and no constexpr!

Thanks to community!

0

There are 0 best solutions below