c++ - 使用显式非类型参数和隐式类型参数调用模板函数

标签 c++ c++11 templates

我想创建一个模板函数,它既有类型模板参数,可以从传递给函数的参数中推导出来,也有非类型模板参数,它们将被显式放置。编译器似乎可以推断出每种类型是什么,但如果我指定非类型模板参数,它需要所有模板参数。我可以只指定非类型模板参数,还是全有或全无?

#include <iostream>
#include <typeinfo>

template <typename T, bool bPrint=true>
void f(T var) {
  if (bPrint)
    std::cout <<  typeid(var).name() << std::endl;
}

int main() {
  f(3); //works
  f<false>(3); //error: template argument deduction/substitution failed
}

最佳答案

可以,但是推导的模板参数需要位于参数列表的末尾。您可以通过重新排序函数模板的参数来编译代码:

template < bool bPrint=true, typename T>
void f(T var) {
  if (bPrint)
    std::cout <<  typeid(var).name() << std::endl;
}

demo

关于c++ - 使用显式非类型参数和隐式类型参数调用模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40874065/

相关文章:

c++ - 实现完美转发到 std::thread 的函数

c++ - 使用 libc++ 在 Mac Yosemite 上访问 std::string 成员时出现链接错误

c++ - 在类模板中使用 = 的类内初始化器

c++ - 尝试使用 boost asio PUT 时出现 Amazon S3 403 错误

c++ - 我应该将什么设置为 _ITERATOR_DEBUG_LEVEL

c++ - 重载策略类​​模板的成员函数

c++ - 类 - 命名空间和模板成员函数特化

C++根据模板参数值更改成员函数定义

c++ - 在 C++ 中使用有界数组的正确方法是什么?

c++ - 专门为私有(private)类(class)的功能?