为什么C ++中的这种部分特化会给编译器错误“无效使用不完整类型”?

时间:2018-01-05 15:33:54

标签: c++ templates template-meta-programming

我正在尝试将一个部分特化添加到一个非常复杂的类中。我试图简化它。

编译器给出错误:

  

main.cpp:43:39:错误:无效使用不完整类型'struct Baz'    Baz :: doSomething(const Foo :: type& a)

     

main.cpp:22:8:注意:'struct Baz'的声明    struct Baz {

我受限于C ++ 03,我怎么能做到这一点?

#include <iostream>

using namespace std;

struct Foo {
    typedef int type;
};

struct Bar {
    typedef int type;
};

template <typename A, typename B>
struct Baz {

    template <typename V>
    struct ReturnType {
        typedef typename V::type type;
    };

    typedef typename ReturnType<B>::type RtType;

    RtType doSomething(const typename A::type& a);
};

template <typename A, typename B>
typename Baz<A, B>::RtType
Baz<A, B>::doSomething(const typename A::type &a)
{
    cout << "In templated implementation" << endl;
}

//// The above is working fine
//// The below is what I'm trying to specializae, and it doens't work.

template <typename B>
typename Baz<Foo, B>::RtType
Baz<Foo, B>::doSomething(const Foo::type& a)
{
    cout << "In partial specialization" << endl;
}

int main()
{
    Baz<Foo, Bar> baz;
    baz.doSomething(3);

    return 0;
}

1 个答案:

答案 0 :(得分:3)

您正尝试在模板类中部分地专门化方法。这是不可能的。你必须对整个班级进行部分专业化。