类型安全的可变参数与相同类型的参数 [英] type-safe variadic functions with parameters of same type

查看:221
本文介绍了类型安全的可变参数与相同类型的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用C ++ 11中引入的类型安全的可变函数,但不能使用不同的类型。
例如:

  template< typename T> 
T maxv(T first,T second){
return first>第二?第一秒;
}

template< typename T,typename ... Rest>
T maxv(T first,T second,T ... rest){
return maxv(first,maxv(second,rest));
}

所有参数的类型都相同,因此可能写入类似:

  struct Point {int x,y; }; 

模板<>
Point maxv(Point first,Point second){
return first.x> second.x?第一秒;
}

maxv({1,2,},{3,4}); // no problem
maxv({1,2,},{3,4},{5,6}); //编译错误

在mingw g ++ 4.5中编译此错误:

 错误:没有匹配的函数调用'maxv(<括号括起始化列表>,&因为他不知道 {






5,6}
的类型为 Point 。解决方案是什么?

解决方案

解决方案是使用可变参数模板!当与函数模板一起使用时,它们用于推断参数的类型。这不是你想做的:你希望参数采取期望的类型。



我没有很多实际经验,但你' d想要为此使用初始化程序列表:

  Point maxv(std :: initializer_list< Point> list){
...
}

您可能会抱怨不能使用任意类型但是你需要意识到,你需要告诉某个地方涉及什么类型。 ...并且它可以做一个模板,虽然你需要指定参数类型。


I want to use type-safe variadic functions introduced in C++11, but not with different types. A example:

template<typename T>
T maxv(T first, T second) {
  return first > second ? first : second; 
}

template<typename T, typename ... Rest>
T maxv(T first, T second, T ... rest) {
  return maxv(first, maxv(second, rest));
}

The type of all parameters are the same, so it is maybe possible to write something like that:

struct Point { int x,y; };  

template<>
Point maxv(Point first, Point second) {
  return first.x > second.x ? first : second; 
}  

maxv({1, 2}, {3, 4});         // no problem    
maxv({1, 2}, {3, 4}, {5, 6}); // compile error

It compiles with this error in mingw g++4.5:

error: no matching function for call to 'maxv(<brace-enclosed initializer list>, <brace-enclosed initializer list>, <brace-enclosed initializer list>)'

Because he do not know that {5, 6} is of type Point. What is the solution?

解决方案

The solution is not to use variadic templates! When used with function templates they are intended to deduce the types of the arguments. That is not what you want to do: you want the arguments to take on the expected type.

I don't have a lot of practical experience with this but you'd want to use initializer lists for this:

Point maxv(std::initializer_list<Point> list) {
    ...
}

You might complain that you can't use this with arbitrary types but then you need to realize that you need to tell somewhere what type are involved. ... And it can be made a template although you'd need to specify the argument type.

这篇关于类型安全的可变参数与相同类型的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆