Array trait causes template argument deduction failure

强颜欢笑 提交于 2019-12-13 06:21:50

问题


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);
}

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’

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);
}

Is the failing code supposed to compile (i.e., did I make a silly mistake)?


回答1:


int foo(typename foo_traits<N>::Function *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.

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



来源:https://stackoverflow.com/questions/17033009/array-trait-causes-template-argument-deduction-failure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!