且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

功能模板中是否允许使用默认功能参数?

更新时间:2023-11-30 19:18:22

BRG写道:
我知道默认模板参数不能在函数模板中使用但默认函数参数合法吗?

就是这样:
----------------------------------
#include< functional>

模板< class T,C类> bool count(T x [],C cmp = std :: less< T>())
{
for(int i = 0; i< 9; ++ i)
if(cmp([i],x [i + 1]))
返回true;
返回false;
}
----------- -----------------------
合法的C ++代码?

int x [10] // - 我应该有添加此行以及计数(x,std :: less< int>()); //编译好,但是
count(x); //给出无法推断''C'的模板参数"
I know that default template arguments cannot be used in function
templates but are default function parameters legal?

That is, is this:
----------------------------------
#include <functional>

template<class T, class C> bool count(T x[], C cmp = std::less<T>())
{
for(int i = 0; i < 9; ++i)
if(cmp([i], x[i + 1]))
return true;
return false;
}
----------------------------------
legal C++ code?
int x[10] // - I should have added this line as well count(x, std::less<int>()); // compiles ok, but
count(x); // gives "could not deduce template argument for ''C''"



Brian Gladman



Brian Gladman


BRG写道:
我知道默认模板参数不能在函数模板中使用但默认函数参数合法吗?
...
I know that default template arguments cannot be used in function
templates but are default function parameters legal?
...




它们是合法的,但它们不会像你期望的那样工作。

模板中不使用函数参数的默认参数

参数演绎程序。


-

祝你好运,

Andrey Tarasevich



They are legal, but they won''t work the way you expect them to work.
Default arguments for function parameters are not used in template
argument deduction process.

--
Best regards,
Andrey Tarasevich


Andrey Tarasevich写道:
Andrey Tarasevich wrote:
BRG写道:
BRG wrote:
我知道默认模板参数不能是用于功能
模板,但默认功能参数是合法的吗?
...
I know that default template arguments cannot be used in function
templates but are default function parameters legal?
...



它们是合法的,但它们不会像你期望的那样工作它们工作。
函数参数的默认参数不用于模板
参数推导过程



They are legal, but they won''t work the way you expect them to work.
Default arguments for function parameters are not used in template
argument deduction process




感谢您的解释 - 但我仍然困惑。在:


------------------

模板< class T,C类> bool count(T x [],C cmp = std :: less< T>())

....

int x [10]

count(x);

....

------------------


模板参数T可以从第一个

函数参数x推断为''int''。因此我不知道为什么扣除涉及

第二个函数参数,因为这似乎是替换(T =>

int)而不是扣除。


我想这是C ++的怪癖。但这是一件令人讨厌的事情,因为我必须在它周围工作。


再次感谢您的帮助。


Brian Gladman



Thanks for the explanation - but I am still puzzled. In:

------------------
template<class T, class C> bool count(T x[], C cmp = std::less<T>())
....
int x[10]
count(x);
....
------------------

the template argument T can be deduced to be ''int'' from the first
function parameter x. I hence don''t see why deduction is involved in
the second function parameter since this seems to be substitution (T =>
int) rather than a deduction.

I guess this is a quirk of C++. But it is a nuisance since I have to
work around it.

Thanks again for your help.

Brian Gladman