这两个可变参数函数之间的本质区别是什么? [英] What's the essential difference between these two variadic functions?

查看:44
本文介绍了这两个可变参数函数之间的本质区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过简单的可变参数模板功能感到沮丧:

  constexpr size_t num_args(){返回0;}模板< typename H,typename ... T>constexpr size_t num_args(){返回1 + num_args< T ...>();}int main(){std :: cout<<num_args< int,int,int>();} 

以上内容未编译,请参见上方链接的问题和后续操作有关详细信息,但以下函数可以编译

  template< typename T,typename ... Args>void foo(T,Args ...);模板< typename ... Args>void foo(int,Args ...);无效foo(){}模板< typename ... Args>无效foo(int x,Args ... args){std :: cout<<"int:"<<X;foo(args ...);}模板< typename T,typename ... Args>void foo(T x,Args ... args){std :: cout<<"T:"<<X;foo(args ...);}foo(int(123),float(123));//打印"int:123 T:123.0" 

两者似乎都使用相同的语言机制,但是当第二个好时为什么第一个坏了?

解决方案

我开始认为区别在于

  foo(args ...); 

利用超载而

  num_args< T ...>(); 

利用专业知识.

重载可以处理基本情况,但不能对函数模板进行特殊化处理(但对于类可以进行特殊处理),这就是 auxilliary_class< Args ...> :: value 惯用的原因.

I've been frustrated by a simple variadic template function:

constexpr size_t num_args () {
    return 0;
}

template <typename H, typename... T>
constexpr size_t num_args () {
    return 1 + num_args <T...> ();
}

int main () {
    std :: cout << num_args <int, int, int> ();
}

The above doesn't compile, see above linked question and followup for details, yet the following function DOES compile

template <typename T, typename... Args> void foo (T, Args...);

template <typename... Args> void foo (int, Args...);

void foo () {}

template <typename... Args>
void foo (int x, Args... args)
{
    std :: cout << "int:" << x;
    foo (args...);
}

template <typename T, typename... Args>
void foo (T x, Args... args)
{
    std :: cout << " T:" << x;
    foo (args...);
}

foo (int (123), float (123)); // Prints "int:123 T:123.0"

Both seem to be using the same language mechanism, but why is the first one bad when the second one is good?

解决方案

I'm starting to think that the difference is that

foo (args...);

exploits overloading whereas

num_args <T...> ();

exploits specialisation.

Overloading can handle the base case but specialisation can't for function templates (but it can for classes) which is why auxilliary_class<Args...>::value is idiomatic.

这篇关于这两个可变参数函数之间的本质区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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