不完整类型(类方法专用化)的使用无效

Invalid use of incomplete type (class method specialization)

本文关键字:无效 专用 类型 类方法      更新时间:2023-10-16

首先,我已经阅读了许多其他问题,但找不到解决方案。 因此,在将其标记为重复项之前,请确保重复回答问题。

我正在尝试专门针对类C2 F::operator();但是,C2有一个模板参数,我希望F::operator()对所有C2的行为都相同。

编译器错误:

error: invalid use of incomplete type ‘struct F<C2<T> >’ void F<C2<T>>::operator()()

另外,我没有Handle& h,而是尝试Handle* h并收到相同的错误。

#include<iostream>
struct C1
{
        void foo()
        {
                std::cout << "C1 called" << std::endl;
        }
};
template<typename T>
struct C2
{
        void bar();
};
template<>
void C2<int>::bar()
{
        std::cout << "C2<int> called" << std::endl;
}
template<typename Handle>
struct F
{
        F(Handle& h_) : h(h_) {}
        void operator()();
        Handle& h;
};
template<>
void F<C1>::operator()()
{
        h.foo();
}
template<typename T>
void F<C2<T>>::operator()()
{
        h.bar();
}
int main()
{
        C1 c1; 
        F<C1> f_c1 (c1);
        f_c1();
        C2<int> c2; 
        F<C2<int>> f_c2 (c2);
        f_c2();
}

没有像成员函数的部分特化这样的事情。您需要首先对整个类进行部分专业化:

template <typename T>
struct F<C2<T>>
{
    void operator()();
};
template <typename T>
void F<C2<T>>::operator()() {}

由于这是一个重量级的解决方案,或者,您可以利用标签调度:

template <typename T> struct tag {};
template <typename Handle>
struct F
{
    F(Handle& h_) : h(h_) {}
    void operator()()
    {
        call(tag<Handle>{});
    }
private:    
    void call(tag<C1>)
    {
        h.foo();
    }
    template <typename T>
    void call(tag<C2<T>>)
    {
        h.bar();
    }
    Handle& h;
};

演示