c++ - 如何在 C++ 中创建和使用非类型模板以及将在何处使用

标签 c++ templates

我正在尝试学习 C++ 中的模板。有人可以解释为什么 sq() 有效而 add() 无效吗?如何修复 add()?非类型模板有什么用?

template <typename T>
inline T sq (const T& x) 
{
    return x*x;
}

template <int*>
inline int add(int* x)
{
   return (*x)*2;
}



int main() {
int x = 2;
cout<<"Square(2): "<<sq(2)<<" Add(2): "<<add(&x)<<endl;
return 0;
}

即使将上面的例子修改如下,还是不行

template <typename T>
inline T sq (const T& x) 
{
    return x*x;
}

template <int>
inline int add(int x)
{
   return x+x;
}



int main() {
    cout<<"Square(2): "<<sq(2)<<" Add(2): "<<add(2)<<endl;
    return 0;
}

最佳答案

我不太确定你在问什么,但你可以使用非类型模板参数,例如,定义一个函数模板,将任何编译时常量添加到它的参数:

template <int N>
inline int add(int x)
{
    return x + N;
}

int main()
{
    std::cout << add<3>(2) << std::endl; // prints 5
    std::cout << add<4>(2) << std::endl; // prints 6
}

回答关于为什么 sq(2) 的具体问题编译但add(&x)不会:函数模板的类型参数可以从函数参数中推导。所以sq(2)相当于sq<int>(2) .无法推导非类型参数,因此您必须提供一个。在指针参数的情况下,参数必须是指向具有外部链接的变量的指针,因此应该编译以下内容:

int global;

int main() {
    int local = 2;
    std::cout << add<&global>(&local) << std::endl;
}

关于c++ - 如何在 C++ 中创建和使用非类型模板以及将在何处使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8745432/

相关文章:

c++ - 使用栈和队列的回文程序

c++ - typename 必须在模板内指定吗?

python - 使用 python 反向模板

C++ 模板复制构造函数,编译器说 "passing const as this argument discards qualifiers"

c++ - 如何将字符串类型的路径传递给 boost::filesystem:path 的构造函数?

c++ - 如何在使用 TCP 的序列化/反序列化中避免跨语言依赖?

c++ - 如何正确显示此枚举类型?

c++ - 模板结构作为数组

c++ - 仿函数 : templated struct vs templated operator()

c++ - 在 C++、QT 中创建 setup.exe