需要说明 [英] Need explanation

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

问题描述



如果我编译以下程序,则编译成功.
以及它运行得很好.一旦运行,就没有输出.

有人请解释
1)该程序如何编译?
2)在这种情况下,模板如何工作?

Hi,

If I compile the following program, it compiles successfully.
As well as it runs very well. Once I run it there is no output.

Anyone please explain
1) How this program compiles ?
2) How does template work in this case ?

template <int iValue>
void Add(int mValue)
{
    printf("I am in Add");
}

int _tmain(int argc, _TCHAR* argv[])
{
      Add<"sss">;
      return 0;
}



在此先感谢.



Thanks in advance.

推荐答案

该行...:

The line...:

Add<"sss">;



实际上不会导致生成任何代码.没有函数调用,没有对象定义.您不是在告诉编译器做任何事情.如果您尝试实际使用功能进行操作:



doesn''t actually cause any code to be generated. There''s no function call, no object definition. You''re not telling the compiler to do anything. If you try actually doing something with your function:

Add<"sss">( 128 );



那么您的编译器将变得合适,而不是构建程序.

干杯,



then your compiler''s going to throw a fit and not build the program.

Cheers,

Ash


如果我这样做
if I do
void func(int x)
{ cout << "in func" << endl; }

int main()
{
   func;
   return 0;
}


由于func不是函数调用,因此不会产生输出.
现在,在我


No outoput will be produced, since func is not a function call.
Now, in I do

template<int N>
void func(int x)
{ cout << "in func" << endl; }

int main()
{
   func<"hhh">;
   return 0;
}


编译器甚至不会生成"func"的代码,因为代码是在需要使用时生成的.

如果我


The compiler will even NOT produce the code for "func", since code is produce at the time it is required to be used.

If I do

int main()
{
   func<"hhh">(128);
   return 0;
}



编译器尝试生成func<"hhh">(int),并且没有办法执行,因此将生成错误.
如果我



The compiler attempt to generate func<"hhh">(int) and have no way to do, hence will generate an error.
If I do

int main()
{
    func<10>(100);
    return 0;
}



编译器生成func<10>(int)并调用它传递100作为参数.

现在,您正确理解了所有这些内容,对您来说应该很清楚
func<10>func<15>是两个不同的功能.



The compiler generates func<10>(int) and calls it passing 100 as a parameter.

Now, you understand all this correctly, it should be clear to you that
func<10> and func<15> are two different and distinct functions.


这篇关于需要说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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