Default Template Arguments in C ++

Suppose I have a StrCompare function template

template<typename T=NonCaseSenCompare>//NonCaseSenCompare is a user defined class look at the detailed code below.
int StrCompare(char* str1, char* str2)
{
...
}

now in the main function i am writing a line

char* str1="Zia";
char* str2="zia";
int result=StrCompare(str1,str2);

it should work because we have provided a default template argument, but it does'nt the compiler give the following error: there is no corresponding function to call `StrCompare (char * &, char * &) 'Now the detailed code is set using

#include<iostream.h>
class CaseSenCompare
{
public: 
static int isEqual(char x, char y)
{
return x==y;
}
};
class NonCaseSenCompare
{
public:
static int isEqual(char x,char y)
{
char char1=toupper(x);
char char2=toupper(y);
return char1==char2;
}
};
template<typename T=NonCaseSenCompare>
int StrCompare(char* str1, char* str2)
{
for(int i=0;i < strlen(str1)&& strlen(str2);i++)
{
if(!T::isEqual(str1[i],str2[i]))
return str1[i]-str2[i];
}
return strlen(str1)-strlen(str2);
}

main()
{
char* ptr1="Zia ur Rahman";
char* ptr2="zia ur Rahman";
int result=StrCompare(ptr1,ptr2);//compiler gives error on this line
cout<<result<<endl;
system("pause");
}

If i write

int result=StrCompare<>(ptr1,ptr2);
Compiler

gives the same error message.

+3
source share
4 answers

gf AndreyT , . , , :

template<typename Comp>
int StrCompare(char* str1, char* str2, Comp = NonCaseSenCompare())
{
  ...
}

StrCompare()

StrCompare("abc","aBc",CaseSenCompare());

:

StrCompare("abc","aBc"); // uses NonCaseSenCompare

:

struct CaseSenCompare {
  bool operator()(char x, char y) const {return x==y;}
};

StrCompare() .

+5

§14.1/9:

- , template-parameter-list .

:

template<typename T=NonCaseSenCompare>
struct StrCompare {
    static int compare(char* str1, char* str2) { /* ... */ }
};
+4

-, , .

Secondly, even if all the parameters of the class template have arguments by default, you still need to specify empty <>to indicate this class template.

+2
source

I use the following trick,

lets say that you want to have such a function

template <typename E, typename ARR_E = MyArray_t<E> > void doStuff(ARR_E array)
{
    E one(1);
    array.add( one );
}

you will not be allowed, but I do the following way:

template <typename E, typename ARR_E = MyArray_t<E> >
class worker {
public:
    /*static - as you wish */ ARR_E* parr_;
    void doStuff(); /* do not make this one static also, MSVC complains */
};

template <typename E, typename ARR_E>
void worker::doStuff<E, ARR_E>::getChunks()
{
    E one(1);
    parr_->add( one );
}

so you can use it like this.

MyArray_t my_array;
worker<int> w;
w.parr_ = &arr;
w.doStuff();

since we cannot explicitly specify the second parameter. perhaps it will be useful for someone.

0
source

Source: https://habr.com/ru/post/1734290/


All Articles