嵌套模板和参数推导

时间:2012-09-28 13:18:01

标签: c++ templates gcc

  

可能重复:
  Workaround for non-deduced context

GCC无法推断出这个“简单”功能的参数。有没有办法帮助编译器一点?

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的

错误消息:

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'

1 个答案:

答案 0 :(得分:3)

虽然它看起来像是一个简单的推论,但是你想让编译器做的事情实际上是非常复杂而且一般来说很慢,并且C ++不支持它。

解决此问题的一种方法是创建另一个非嵌套类,该类在一个位置包含所有模板参数。然后,您可以通过派生它使它看起来像一个嵌套类:

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还支持模板别名,这使得它更加清晰,尽管它还没有被广泛支持:

template<int a> struct A
{
    template<int b> using B = A_B<a,b>;
};

这个问题密切相关:

Workaround for non-deduced context

这里提供的答案对您的情况也很有用。如果你可以让你的功能成为朋友,那么你可以这样做:

template<int a> struct A
{
    template <int b>
    struct B
    {
    };

    template <int b>
    friend void test(B<b> param)
    {
    }
};
相关问题