使用extern模板函数时编译错误

时间:2015-09-07 17:46:34

标签: c++

这是question的延续。得到编译错误

g++ -fpermissive -std=c++11 te2b.cc te2d.cc
/tmp/ccUVm8OV.o: In function `notify(std::string, int)':
te2b.cc:(.text+0x80): undefined reference to `void notify<char const*>(char const*, char const*&&)'
/tmp/ccUVm8OV.o: In function `main':
te2b.cc:(.text+0xe6): undefined reference to `void notify<int>(char const*, int&&)'
collect2: error: ld returned 1 exit status

猜测我的extern是否模板功能未被声明正确,不知道如何纠正它。有任何想法吗?谢谢!

====== te2b.cc ======

#include <vector>
#include <iostream>
#include <unordered_map>
#include <stdarg.h>
using namespace std;

extern char notifyBuf[];
template <typename ... Ts>
extern void notify(const char* format, Ts&&... args);
void notify(string s, int maxSize=0) {
    if (maxSize && (maxSize < s.size())) {
        s.erase(maxSize);
    }
    printf("second invokation\n");
    notify("%s\n", s.c_str());
}
int main(int argc, char *argv[]) {
    string s = "hi tom";
    //notify(s);
    notify("hi %5d \n", 89);    
    printf("%s\n", &notifyBuf[0]);
    notify(s, 5);
    printf("%s\n", &notifyBuf[0]);
    return 0;
}

====== te2d.cc =======

#include <sys/shm.h>
#include <malloc.h>
#include <unordered_map>
#include <string>
#include <iostream>
typedef unsigned char uchar;
typedef unsigned short uint16;
using namespace std;

char notifyBuf[0x100000] = "s";
template <typename ... Ts>
void notify(const char* format, Ts&&... args)  {
    sprintf(&notifyBuf[1], format, std::forward<Ts>(args)...);
}

0 个答案:

没有答案