可变参数模板示例

例如

考虑下面的代码,我不明白为什么必须定义空白的打印功能。

#include <iostream>
using namespace std;

void print()
{   
}   

    template <typename T, typename... Types>
void print (const T& firstArg, const Types&... args)
{   
    cout << firstArg << endl; // print first argument
    print(args...); // call print() for remaining arguments
}

int main()
{   
    int i=1;
    int  j=2;
    char c = 'T';
    print(i,"hello",j,i,c,"word");

}   
咖啡开发者

正确的方法:

可变参数模板与induction数学概念严格相关

编译器解析以下函数调用

print('a', 3, 4.0f);

进入

std::cout<< 'a' <<std::endl;
print(3, 4.0f);

解析为

std::cout<< 'a' <<std::endl;
std::cout<< 3 <<std::endl;
print( 4.0f);

解析为

std::cout<< 'a' <<std::endl;
std::cout<< 3 <<std::endl;
std::cout<< 4.0f <<std::endl;
print();

此时,它搜索匹配为空函数的函数重载。

  • 具有1个或多个参数的所有函数均与可变参数模板匹配
  • 所有没有参数的函数都与空函数匹配

罪魁祸首是,对于每种可能的参数组合,您必须仅具有1个功能。


错误1:

进行以下操作将是错误的

template< typename T>
void print( const T& arg) // first version
{   
    cout<< arg<<endl;
}   

template <typename T, typename... Types>
void print (const T& firstArg, const Types&... args) // second version
{   
    cout << firstArg << endl; // print first argument
    print(args...); // call print() for remaining arguments
}

因为当您调用print编译器时,它不知道要调用哪个函数。

是否print(3)指的是“第一”或“第二”的版本?两者都是有效的,因为第一个有1个参数,第二个也可以接受一个参数。

print(3); // error, ambiguous, which one you want to call, the 1st or the 2nd?

错误2:

无论如何以下都是错误

// No empty function

template <typename T, typename... Types>
void print (const T& firstArg, const Types&... args) 
{   
    cout << firstArg << endl; // print first argument
    print(args...); // call print() for remaining arguments
}

实际上,如果不使用编译器就单独使用它

 print('k', 0, 6.5);

解析为

 std::cout<<'k'<<std::endl;
 print(0, 6.5);

解析为

 std::cout<<'k'<<std::endl;
 std::cout<< 0 <<std::endl;
 print( 6.5);

解析为

 std::cout<<'k'<<std::endl;
 std::cout<< 0 <<std::endl;
 std::cout<< 6.5 <<std::endl;
 print(); //Oops error, no function 'print' to call with no arguments

如您在上一次尝试中看到的,编译器尝试不print()带任何参数的调用。但是,如果不存在这样的函数,则不会调用它,这就是为什么您应该提供该空函数(不用担心,编译器会优化代码,因此空函数不会降低性能)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章