数组trait导致模板参数扣除失败 [英] Array trait causes template argument deduction failure

查看:138
本文介绍了数组trait导致模板参数扣除失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码不使用G ++编译(虽然我相信它应该):

The following code does not compile with G++ (although I believe it should):

#include <iostream>

template <unsigned N>
struct foo_traits {
    typedef const char ArrayArg[N];
    typedef int Function (ArrayArg *);
};

template <unsigned N>
int foo (typename foo_traits<N>::Function *ptr) {
    return ptr(&"good");
}

int bar (const char (*x)[5]) {
    std::cout << *x << "\n";
    return 0;
}

int main ()
{
    return foo(bar);
}

我用GCC 4.4到4.7检查了这个,我得到了一个模板参数扣除失败。与4.7.1:

I checked this with GCC 4.4 through 4.7, and I get a template argument deduction failure. With 4.7.1:

prog.cpp: In function ‘int main()’:
prog.cpp:21:19: error: no matching function for call to ‘foo(int (&)(const char (*)[5]))’
prog.cpp:21:19: note: candidate is:
prog.cpp:10:5: note: template<unsigned int N> int foo(typename foo_traits<N>::Function*)
prog.cpp:10:5: note:   template argument deduction/substitution failed:
prog.cpp:21:19: note:   couldn't deduce template parameter ‘N’


$ b c> foo 5(bar)),它编译得很好。如果我使用没有 typedef 的代码版本,它编译得很好:

If I use an explicit template argument (i.e., foo<5>(bar)), it compiles fine. If I use a version of the code without the typedefs, it compiles fine:

#include <iostream>

template <unsigned N>
int fixfoo (int (*ptr) (const char (*)[N])) {
    return ptr(&"good");
}

int bar (const char (*x)[5]) {
    std::cout << *x << "\n";
    return 0;
}

int main ()
{
    return fixfoo(bar);
}

是失败的代码应该编译一个愚蠢的错误)?

推荐答案

int foo(typename foo_traits<N>::Function *ptr);

签名使其成为不可抵扣的上下文,因此您必须模板参数,使得值 N 是已知的,因此,也可以知道指针 ptr 的类型。

The signature makes it a non-deductible context, so you must include the template arguments so that the value N is known and so consequentially the type of the pointer ptr be known as well.

您的第二个示例编译,因为可以推导出 bar 的签名类型。

Your second example compiles because the type of the signature through bar can be deduced.

这篇关于数组trait导致模板参数扣除失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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