【问题标题】:C++: Passing arguments through templates Vs through function parametersC++:通过模板传递参数与通过函数参数
【发布时间】:2017-03-03 11:36:26
【问题描述】:

通过模板发送参数有什么目的吗?如果是这样,这与通过内部堆栈发送参数有何不同?示例:

void myMethod(int argument){//Do something with *argument* };

对

template<int argument>
void myMethod(){//Do something with *argument* };

在Thinking in C++一书中,第1卷,第2版,在Templates in depth一章下,关于非类型模板参数只有几句话,而且我觉得我还没有完全理解他们的目的。

编辑:感谢您的解释。如果可以,我会标记这两个答案,因为它们相互补充。

【问题讨论】:

  • 模板参数是编译时间常数。例如,当argument 是模板时,您可以在语句 `std::array' 中使用它。

标签: c++ oop templates


【解决方案1】:

不同之处在于,模板的值是在编译时决定和固定的;即,当您编译程序时。编译完成后,您永远无法更改它们,并且它们永远被视为常量。

所以,用:

template<int argument>
void myMethod(){//Do something with *argument* };

如果你调用myMethod&lt;5&gt;(),那么argument 的值总是5,并且函数在运行时实际上没有任何参数。现在,如果您调用myMethod&lt;6&gt;(),编译器将重新创建相同的函数,但使用另一个常量值。因此,您将在运行时拥有 2 个函数。

另一方面,使用普通方法,您可以在运行时更改它们,即在程序运行时。再次调用该函数只会执行具有不同参数值的相同代码。

例子:

template <int L>
void DoSomething()
{
    int a[L];  //this works fine here! Becasue L is just a constant that is resolved at compile-time
    for(int i = 0; i < L; i++)
    {
        //do stuff
    }
}


void DoSomething(int L)
{
    int a[L];  //this won't work, because L is a variable that can be set while the program is running
    for(int i = 0; i < L; i++)
    {
        //do stuff
    }
}

【讨论】:

  • 这有点像constexpr 强调的谎言,但确实是这样。
【解决方案2】:

这里:

void myMethod(int argument){//Do something with *argument* };

参数在运行时传递给myMethod,因此可以传递不同的值。

这里:

template<int argument>
void myMethod(){//Do something with *argument* };

argument模板参数在编译时传递。

非类型模板参数在与类一起使用时具有更大的含义,即:

template<int N>
class Test{};

typedef Test<1> test1_type;
typedef Test<2> test2_type;

static_assert(std::is_same<test1_type, test2_type>::value == false, "");

test1_type 和test2_type 是不同的类型

【讨论】:

  • 您在第二个示例中缺少&lt;type argument&gt;。
  • @FabianKlötzl 已修复
猜你喜欢
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 2023-03-26
相关资源
最近更新 更多