【发布时间】:2019-03-07 16:47:07
【问题描述】:
在我的代码中,通常我必须编写一个采用“类路径”类型的函数,即可以转换为boost::filesystem::path 的函数,例如
QStringstd::string-
const char * - 等等……
在 A.hpp 中
struct A
{
template <typename PathLike>
void myFunction(PathLike path);
};
在 A.cpp 中
template <typename PathLike>
void A::myFunction(PathLike path)
{
boost::filesystem::Path p = convertToBoostPath(path);
//do something...
}
//Explicit instantiations needed
template void A::myFunction(string);
template void A::myFunction(QString);
template void A::myFunction(char const *);
//....
问题是,如果我想在不同的函数B 中做同样的事情,我需要重新添加显式实例化。也许我采取了错误的方法。
【问题讨论】:
-
为什么不在头文件中定义函数呢?如果需要,您可以使用 SFINAE 来约束类型。
标签: c++ templates metaprogramming