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

Invalid use of incomplete type (class method specialization)

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

我正在尝试将 F::operator() 专门化为 class C2;然而,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();
}

没有像成员函数的偏特化这样的东西。您需要首先部分专业化整个 class:

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

DEMO