gpt4 book ai didi

c++ - 不完整类型的无效使用(类方法特化)

转载 作者:行者123 更新时间:2023-11-30 03:43:27 25 4
gpt4 key购买 nike

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

我正在尝试专攻 F::operator()上课 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()() {}

由于这是一个重量级的解决方案,或者,您可以利用标签分派(dispatch):

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

关于c++ - 不完整类型的无效使用(类方法特化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36079774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com