模板和默认参数...... [英] Templates and default arguments ...

查看:122
本文介绍了模板和默认参数......的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的专家,我有这段代码:



Dear experts, I have this piece of code:

template <typename genericType = int>
genericType add (genericType a, genericType b)
{
  return a + b;
}

int main ()
{
 int i1 = 1;
 double d2 = 3.14;
 
std::cout << "Add: " << add<> (i1,d2) << std::endl;

return 0;
}



它在编译时给出了以下错误:




it gives me the following error at compile time:

test.cpp:14:27: error: no matching function for call to 'add'
  std::cout << "Add: " << add<> (i1,d2) << std::endl;
                          ^~~~~
test.cpp:4:13: note: candidate template ignored: deduced conflicting types for parameter 'genericType' ('int' vs. 'double')
genericType add (genericType a, genericType b)
            ^
1 error generated.



有没有办法可以将参数转换为int?

我认为可以使用默认模板值。



非常感谢,

- Mauro。< br $> b $ b

我的尝试:




Is there a way that I can cast the arguments to be int?
I thought it was possible with the default template value.

Many thanks,
- Mauro.

What I have tried:

template <typename genericType = int>
genericType add (genericType a, genericType b)
{
  return a + b;
}

int main ()
{
 int i1 = 1;
 double d2 = 3.14;
 
std::cout << "Add: " << add<> (i1,d2) << std::endl;

return 0;
}

推荐答案

您已将默认类型声明为 int 所以它期望这两个论点。请参阅模板(C ++) [ ^ ]以获得完整的解释。
You have declared the default type to be int so it expects that for both arguments. See Templates (C++)[^] for full explanation.


不,那不是工作。既然你为 a b 指定了 genericType 那么那些参数必须具有相同的类型,否则模板参数推断失败。

顺便说一下模板默认参数没有效果,因为编译器总是可以推导出 genericType 从实际函数参数类型中键入。
Nope, that doesn't work. Since you specified genericType for both a and b then those arguments must have the same type, otherwise template argument deduction fails.
By the way the template default argument has no effect, since the compiler can always deduce genericType type from actual function argument type(s).


这篇关于模板和默认参数......的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆