Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ templates, vector.size used in default parameter definitoin

There is a structure TA

template <typename T>
struct TA
{
    typedef std::vector <T> Type;
};

and test() function having a default parameter of the type TA.

template <typename T>
void test ( typename TA<T>::Type a1, 
            typename TA<T>::Type a2 = typename TA<T>::Type(a1.size()) )
{}

Is it posssible to use a1.size() in default parameter a2 definition?

int main()
{
    TA <double> ::Type a1;
    test<double>(a1);
}
like image 936
justik Avatar asked Dec 16 '22 04:12

justik


1 Answers

Is it posssible to use a1.size() in default parameter a2 definition?

No. It is forbidden by the Standard. You cannot use function parameter to set the default value of other parameter.

§8.3.6/9 (C++03) explicitly says,

Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in default argument expressions, even if they are not evaluated.

So the solution is: use overload:

template <typename T>
void test(typename TAs<T>::Type a)
{
    test(a, typename TA<T>::Type(a.size()));
}
like image 189
Nawaz Avatar answered May 19 '23 13:05

Nawaz