提问人:vrdhn 提问时间:3/18/2018 最后编辑:vrdhn 更新时间:3/18/2018 访问量:42
模板化方法的未解析符号专用化
unresolved symbol specialization of templatized method
问:
此代码无法解析 。void K::func<B>(B&)
struct K {
template <typename T> void func(T &t);
};
struct B {
void ok();
};
// definition
template <typename T> void K::func(T &t) { t->ok(); }
// getting: undefined reference to `void K::func<B>(B&)'
// nm says ' U void K::func<B>(B&)'
template <> void K::func<B>(B &b);
template <> void K::func(B &b);
int main() {
K k;
B b;
k.func(b);
};
注:SO的其他几个问题与编译有关;我 m 卡在链接上。如果有的话,请指出我重复。
更新: 我跟着 http://en.cppreference.com/w/cpp/language/template_specialization,寻找函数g1或g2;
UPDATE2:将“func”修复为“K::func”以修复“类外成员模板定义”,仍然无法对 K::func 进行专用化。
答:
3赞
Yola
3/18/2018
#1
您需要提供如下定义:
template <> void K::func<B>(B &b) {}
此外,以下两个是等价的,仅在第二种情况下,T 是从参数类型中推导出来的:
template <> void K::func<B>(B &b);
template <> void K::func(B &b);
评论
0赞
vrdhn
3/18/2018
我有..问题是如何将其专门用于 T = B !,而不是重新定义 T = B 的 functemplate <typename T> void func(T &t) { t->ok(); }
0赞
Yola
3/18/2018
@vrdhn,但此模板与 无关。对于结构 K,您可以编写 .struct K
template<> void K::func(B &b) { b.ok(); }
0赞
vrdhn
3/18/2018
哦,是的。。谢谢,我想我需要另一只付费眼睛(-:但是,这个定义需要为我的用例模板化。
0赞
vrdhn
3/18/2018
但是对于几个 B、C、D 类,我需要重新实现它。
0赞
vrdhn
3/18/2018
#2
事实证明,这只是一个声明,因为需要定义。更新后的代码:template <> void K::func(B &b);
template void K::func(B &b);
struct K {
template <typename T> void func(T &t);
};
struct B {
void ok();
};
// definition
template <typename T> void K::func(T &t) { t.ok(); }
// specialiation: Do NOT put template <> here !!!
template void K::func(B &b);
int main() {
K k;
B b;
k.func(b);
};
评论
K::func
B::ok