简体   繁体   中英

Default parameters in template functions (C++)

I'm trying to use default parameters in a template function. The following is a minimal example of the thing I'm trying to do:

In sort.h

template <typename T0, typename T1>
void sort(Vector<T0> &v0,Vector<T1> &v1=0)
{
    //sort v0, if (v1 != 0) sort it according to v0
}

In main.cpp

#include "sort.h"
Vector<int> v0;
sort(v0);

This does not compile; the compiler gives the error "no matching function to call to 'sort'".

Basically this function should sort the vector v0 (arbitrary datatype). In addition, a second vector v1 (arbitrary) which is sorted in the same way as vector v0 can be given as parameter. Of course I could solve this problem simply by using overloaded functions, but since I'd like to expand the list of additional vectors up to 5, I would need like hundreds of different functions.

Update: Thanks for your responses so far. I have modified my problem description to give you a better idea of what I'm trying to do.

引用不能指向任何内容。

You cannot default a reference to 0. You'd have to use pointers to do this (if you insist).

There's also no way for the compiler to intuit what T1 is without an actual Vector<X> to work from. A concrete parameter type would be needed for parameter 2. If the second parameter was Vector<T0>* , for example, that would be OK since the type can be divined from parameter 1 (which is not defaulted). Otherwise, you'll have to specify the template parameters on every call to testfunction .

Adding info on what you are trying to achieve might enable better answers to be provided. This seems a little convoluted.

I would just simply overload the function.

template <typename T0, typename T1>
void sort(Vector<T0> &v0,Vector<T1> &v1)
{
    //do something
}
void sort(Vector<T0> &v0)
{
    //do something
}

I would prefer

template <typename T0, typename T1>
void testfunction(Vector<T0> &v0,const Vector<T1> &v1 = Vector<T1>() )
{
    //do something
}

Just because you're giving a default value for the second argument in testfunction, the compiler has no way of deriving T1 if you don't give it something to go on. You need to explicitly state the type. Something like:

testfuntion<int, float>(v0);

Also, as others have pointed out, you need to find some way of properly declaring the second argument since a reference can't have "null" value. I personally like this way .

You'll have to change it to use pointers instead:

template <typename T0, typename T1>
void testfunction(Vector<T0>* v0, Vector<T1>* v1 = 0)
{
    //do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM