c++ - 非类型模板参数与函数参数

标签 c++ templates parameters arguments

我写了一个简单的例子,它以某种方式编译。

#include <iostream>
using namespace std;

template <int A>
void func()
{
    cout << 1 + A << endl;
    return;
}

int main()
{
    // I can not even use this strange func()
    int a = 1; func(a); // this does not compile
    func(1);            // this does not compile as well 
    return 0;
}

这个例子让我很沮丧:

首先,我给了模板非类型模板参数,但没有提供任何参数(在括号中)来运行它自己。看起来模板参数变成了函数参数,但为什么?

其次,即使它编译了,我也找不到使用这个模板的方法,请参阅我在 main 中的评论。

第三,非整型模板参数的模板函数存在的原因是什么?它与具有常规功能有何不同?

最佳答案

int A 不是函数参数,它是模板参数。 func 不接受任何参数,您可以像这样实例化/调用它:

func<1>(); // compile-time constant needed

请查看 C++ 函数模板。您不能以您想要的方式使用模板参数。

另一方面,有一个类型模板参数和一个函数参数:

template <typename A>
void func(A a)
{
    cout << 1 + a << endl;
}

将使您的程序有效。也许这就是您想要的。

编辑:

根据您的要求,下面是这种非类型函数模板参数的用法:

template <size_t S>
void func(const int (&array)[S])
{
    cout << "size of the array is: " << S << endl;
}

std::array版本:

template <size_t S>
void func(std::array<int, S> const& array)
{
    cout << "size of the array is: " << S << endl;
}

S 这里被推导为传递的数组的大小。

关于c++ - 非类型模板参数与函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384407/

相关文章:

c++ - 使用 lambdas 移动

c++ - 当重载方法将模板类作为参数时会发生什么

c++ - 如何在 for 循环中使用 const 变量来生成模板类?

C# 使用管道和符号传递多个枚举值之间的区别

mysql - nodejs 表达 mysql 查询 'SET @' XXX''

c++ - 在 C++ 中没有修饰符的 RegisterHotKey

c++ - 错误] 无法通过 'std::string {aka class std::basic_string<char>}' 传递非平凡可复制类型 '...' 的对象

c++ - 在未来的 C++ 中优雅地避免 vector 元素的值初始化?

css - Rails 应用程序中的主题

javascript - 如何使用长参数列表保持 javascript 代码简单和有条理?