2013-03-08 54 views
1

我使用以下代码片段获取未解析的外部程序编译错误。使用C++ lambda的未解析外部程序

acquire_gray(identity, []{}); 

samething发生在我尝试使用auto

auto acquire_callback = [](LPBITMAPINFOHEADER pbi, HANDLE hdib) 
    { 
      printf("Callback\n"); 
    }; 

    acquire_gray("", acquire_callback); 

,但是当我通过在空它编译

acquire_gray(identity, NULL); 

这是我的计划

driver.cpp的结构

#include "bridge.h" 

void TB_AcquireImagesStart(HANDLE hNamedPipe, const TB_Message request) 
{ 
    acquire_gray("", []{}); 
} 

bridge.h

template<typename T> 
void acquire_gray(const string_t& identity, T& callback); 

bridge.cpp

template<typename T> 
void acquire_gray(const string_t& identity, T& callback) 
{ 
    callback(); 
} 

所以两个例外,我越来越有

Error 12 error LNK1120: 1 unresolved externals 

Error 11 error LNK2019: unresolved external symbol "void __cdecl acquire_gray<class <lambda_e125ff607fe0339bba6077ce9c14d586> >(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &,class <lambda_e125ff607fe0339bba6077ce9c14d586> &)" ([email protected]<lambda_e125ff607fe0339bba6077ce9c14d586>@@@@[email protected][email protected]@[email protected]@[email protected]@[email protected]@[email protected]@AAV<lambda_e125ff607fe0339bba6077ce9c14d586>@@@Z) referenced in function "void __cdecl TB_AcquireImagesStart(void *,class TB_Message)" ([email protected]@[email protected]@@Z) 

所以我的问题是,什么是错的我代码,我该如何解决这个问题,为什么auto没有检测到我的lambda类型。

+4

您不能将模板函数定义放在单独的'.cpp'文件中。编译器不会看到它们。尝试在'bridge.h'中放置'acquire_gray <>()'的定义 – 2013-03-08 17:30:52

回答

3

你不能在.cpp中放置模板定义(你可以,但只有在编译单元中使用它们才有意义)。编译后,只存在模板实例。

2

这只是使用模板时常见的错误。你不能(或至少不应该)将模板分隔成头(.hpp)和源(.cpp)文件。详细信息请参见here