相关疑难解决方法(0)

隐藏功能模板,声明专业化

这是C++模板的后续内容:防止基本模板的实例化

我使用模板来实现函数重载而不会出现隐式类型转换:声明函数模板,定义所需的特化(重载).一切都很好,除了错误的代码在链接阶段之前不会产生错误:

lib.hpp:

template<class T> T f(T v);
Run Code Online (Sandbox Code Playgroud)

lib.cpp:

#include "lib.hpp"

template<> long f(long v) { return -v; }
template<> bool f(bool v) { return !v; }
Run Code Online (Sandbox Code Playgroud)

main.cpp中:

#include <iostream>
#include "lib.hpp"

int main()
{
    std::cout
        << f(123L) << ", "
        << f(true) << ", "
        << f(234) << "\n"
    ;
}
Run Code Online (Sandbox Code Playgroud)

gcc输出:

c++ -O2 -pipe -c main.cpp
c++ -O2 -pipe -c lib.cpp
c++ main.o lib.o -o main
main.o(.text+0x94): In function `main':
: undefined reference …
Run Code Online (Sandbox Code Playgroud)

c++ templates declaration template-specialization

2
推荐指数
1
解决办法
2058
查看次数