为什么这个可变函数模糊? [英] Why is this variadic function ambiguous?

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

问题描述

这与我较早的文章有关。我想知道为什么一个尝试的解决方案不起作用。

This is related to my earlier post. I'd like to know why one attempted solution didn't work.

template <typename... T>             /* A */
size_t num_args ();

template <>
size_t num_args <> ()
{
    return 0;
}

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



如果我尝试调用,说: num_args< int,float>()那么错误是函数调用是不明确的:

If I try to call, say, num_args<int,float>() then the error is that the function call is ambiguous:


  • {int,float}

  • B H = int,T = {float}

我不明白这是如何含糊的 - A是一个声明,B是A声明的函数的定义。对吗?

I don't understand how this is ambiguous -- A is a declaration and B is a definition of the function declared by A. Right?

我试图使这个示例工作,对我之前的问题的回复似乎

I'm trying to make this example work and the responses to my earlier question seem to claim that it can never work.

如果是这样,可变自由功能的重点是什么?

推荐答案


我不明白这是一个歧义 - A是一个声明,B
是由A声明的函数的定义。对吗?

I don't understand how this is ambiguous -- A is a declaration and B is a definition of the function declared by A. Right?

没有。 A是函数模板的声明,B是另一个函数模板的声明(和定义)。

No. A is a declaration of a function template, and B is a declaration (and definition) of another function template.

编译器没有办法在两者之间决定:它们都没有参数,模板参数是两者的匹配。

The compiler has no way to decide between the two: they both have no arguments, and the template arguments are a match for both.

中间的一个是显式的函数的特殊化模板在A中声明。

The one in the middle is an explicit total specialization of the function template declared in A.

如果您尝试让B另一个专业化A:

If you tried to make B another specialization of A:

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

...你最终会得到一个函数模板的部分特化,这是不允许的。

... you'd end up with a partial specialization of a function template, which is not allowed.

你可以通过使用带有部分特化的类模板和调用类模板的函数模板的常规技巧来做到这一点: p>

You can do this with the usual trick of using a class template with partial specializations and a function template that calls into the class template:

template <typename... T>
class Num_Args;

template <>
struct Num_Args <>
{
    static constexpr size_t calculate() {
        return 0;
    }
};

template <typename H, typename... T>
struct Num_Args <H, T...>
{
    static constexpr size_t calculate() {
        return 1 + Num_Args<T...>::calculate();
    }
};

template <typename... T> /* B */
constexpr size_t num_args ()
{
    return Num_Args<T...>::calculate();
}

这篇关于为什么这个可变函数模糊?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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