嵌套模板和参数推导 [英] Nested template and parameter deducing
问题描述
可能重复:
非推导上下文的解决方法
GCC无法推导参数为这个简单的功能。有没有办法帮助编译器一点?
GCC cannot deduce parameters for this 'simple' function. Is there any way to help the compiler a bit?
template<int a> struct A
{
template<int b> struct B
{
};
};
template<int a, int b> void test(typename A<a>::template B<b> param) { }
int main()
{
A<1>::B<2> b;
test<1,2>(b); // works
test(b); // doesn't work
}
来自GCC的错误消息4.7.1: p>
error message from GCC 4.7.1:
test.cpp: In function 'int main()':
test.cpp:15:8: error: no matching function for call to 'test(A<1>::B<2>&)'
test.cpp:15:8: note: candidate is:
test.cpp:8:29: note: template<int a, int b> void test(typename A<a>::B<b>)
test.cpp:8:29: note: template argument deduction/substitution failed:
test.cpp:15:8: note: couldn't deduce template parameter 'a'
推荐答案
看起来像一个简单的演绎,你想要的编译器做的实际上是相当复杂和一般的慢,做不到C + +。
Although it seems like a simple deduction, what you are wanting the compiler to do would actually be quite complicated and slow to do in general, and it isn't supported by C++.
其中一种方法是创建另一个非嵌套类,它在一个地方具有所有模板参数。然后可以通过派生它来使它看起来是一个嵌套类:
One way around this is to create another non-nested class that has all the template parameters in one place. You can then make this appear to be a nested class by deriving from it:
template<int a,int b> struct A_B {
/* define your class here */
};
template<int a> struct A
{
template<int b> struct B : A_B<a,b> {/*nothing here*/};
};
template<int a, int b> void test(A_B<a,b> param) { }
int main()
{
A<1>::B<2> b;
test<1,2>(b); // works
test(b); // works too
}
C ++ 11也支持模板别名,虽然它还没有得到广泛支持:
C++11 also supports template aliasing, which makes this a little cleaner, although it isn't widely supported yet:
template<int a> struct A
{
template<int b> using B = A_B<a,b>;
};
这个问题密切相关:
未推演的上下文的解决方法
Workaround for non-deduced context
提供的答案对您的情况也很有用。如果你能让你的功能成为朋友,你可以这样做:
The answers provided there are useful for your situation as well. If you can make your function be a friend, then you can do this:
template<int a> struct A
{
template <int b>
struct B
{
};
template <int b>
friend void test(B<b> param)
{
}
};
这篇关于嵌套模板和参数推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!