[英]Templated member function of non-templated struct/class - what's the default type?
I've seen code like this: 我看过这样的代码:
#include <iostream>
// member_function_templates.cpp
struct X
{
template <class T> void mf(T* t) {
std::cout << "in mf t is: " << *t << std::endl;
}
};
int main()
{
int i = 5;
X* x = new X();
x->mf(&i); //why can this be called without specifying a type as in: x->mf<int>(&i) ??
}
My question is in the comment there in main. 我的问题在主要评论中。 Why can you call: 为什么要打电话给:
x->mf(&i);
...without specifying a type? ...没有指定类型? Intuition says it should be called like: 直觉说应该这样称呼:
x->mf<int>(&i);
... but apparently does not have to be called like this (the above compiles with gcc 4.7 for me either way - with of without explicitly specifying the template.) ...但是显然不必这样调用(以上方法对我来说都是用gcc 4.7编译的-带有,而没有明确指定模板。)
And, if you call it without specifying a type for the template, what will the type of T be (in the template function definition)? 而且,如果您在未指定模板类型的情况下调用它,则T的类型将是什么(在模板函数定义中)? (I'm guessing it defaults to the type of whatever it is you pass into the function mf as an argument, but further explanation of how this works would be nice) (我猜它默认为您传递给函数mf作为参数的类型,但是进一步解释它的工作方式会很好)
That is template type deduction and it applies to all template functions, not just members of a non-templated class. 那就是模板类型的推导,它适用于所有模板函数,而不仅仅是非模板类的成员。 Basically the compiler is able to infer (following a set of rules in the standard) what the type T
means from the arguments to the function. 基本上,编译器能够推断(遵循标准中的一组规则)从参数到函数的类型T
含义。 When the compiler sees the call to mf(&i);
当编译器看到对mf(&i);
的调用时 , it knows that i
is an int
, so the argument is an int*
and that means that you want the overload that has T==int
(*) ,它知道i
是一个int
,所以参数是一个int*
,这意味着您想要具有T==int
(*)的重载
You can still provide a particular set of template arguments if you want to force a particular specialization of the template. 如果要强制对模板进行特殊的设置,则仍可以提供一组特定的模板参数。 If, for example, you want the parameter to the template not be the deduced one, but one that is convertible from it: 例如,如果您不希望模板的参数是推导的参数,而是可以从模板转换的参数:
template<typename T>
void foo(T arg) {...}
int i = 10;
foo(i); // calls foo<int>(i)
foo<double>(i); // calls foo<double>(static_cast<double>(i))
(*) It is slightly more complicated than this, as there could be potentially multiple T
types for which the argument would be valid, but the rules in the language determine what particular T
will be deduced . (*)比这稍微复杂一点,因为可能存在多种T
类型,其参数将对其有效,但是该语言中的规则确定要推导出的特定T
In this case, it is int
. 在这种情况下,它是int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.