LNK2019-为什么未解决的具有模板好友功能的外部 [英] LNK2019 - why unresolved external with template friend function

查看:45
本文介绍了LNK2019-为什么未解决的具有模板好友功能的外部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有收到此错误:

#include <iostream>
using namespace std;

// LNK2019f.cpp
// LNK2019 expected
template<class T>
void f(T) {}

template<class T>
struct S {
   friend void f(T);
   // try the folowing line instead
   // friend void f<T>(T);
};

int main() {
   S<int> s;
   int a = 2;
   f(a);   // unresolved external
}

来自 http://msdn.microsoft.com/en-us/library/799kze2z(v = vs.80).aspx

如果我注释掉 S<为什么没有显示错误?int> s ?我知道也需要声明模板参数列表,但是我看不到该模板化结构与 f(a)调用之间的联系.

Why does the error not show up if I comment out S< int > s ? I got that I need to declare the template argument list as well, but I don't see the connection between that templated structure and the f(a) call..

另一件事很奇怪:如果我仅注释掉 f(a)调用(其余所有内容都留在原处),它将再次编译.我正在使用MSVC2012.

Another weird thing: if I comment out just the f(a) call (and I leave all the rest in place), it compiles again. I'm using MSVC2012.

推荐答案

发生此错误是因为您的朋友声明充当另一个未模板化的 f 函数的函数声明.

The error occurs because your friend declaration acts as a function declaration of another non-templated f function.

您必须像这样声明它,以便告诉编译器它是模板函数:

You have to declare it like this in order to tell the compiler that it is a template function:

    friend void f<T>(T);

请考虑以下示例:

template<class T>
struct S {
    friend void foo(int);
};

int main() {
    S<int> s;
    foo(42);
}

这将引发链接器错误,提示此处未解析的外部符号 foo .在这种情况下,声明了 foo ,但未通过好友声明进行定义.

This will throw a linker error muttering about an unresolved external symbol foo here. In this case foo is declared but not defined through the friend declaration.

如果我们现在注释掉 S< int>s; 我们现在不是链接器,而是编译器错误:'foo':找不到标识符,因为尚未将 foo 声明为S< int> 未编译.

If we now comment out S<int> s; we now get not a linker but a compiler error: 'foo': identifier not found, because foo has not been declared, as S<int> isnt compiled.

这篇关于LNK2019-为什么未解决的具有模板好友功能的外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆