pro*_*ian 8 c++ templates visual-c++
我有模板专业化的问题,我想了解.我正在使用Visual C++ 10.0(2010).我有一个这样的课:
class VariableManager
{
public:
template<typename VarT>
VarT get(std::string const& name) const
{
// Some code...
}
// This method supposed to be fully evaluated, linkable method.
template<>
std::string get<std::string>(std::string const& name) const;
private:
std::map<std::string, boost::any> mVariables;
};
Run Code Online (Sandbox Code Playgroud)
理论上,因为我专门使用"get"方法,所以链接器应该能够从目标文件中获取.相反,如果我将方法放在源文件中,我会得到一个未解决的链接器引用错误:
template<>
std::string VariableManager::get<std::string>(std::string const& name) const
{
// Doing something...
}
Run Code Online (Sandbox Code Playgroud)
如果我将此方法作为内联放在头文件中,那么构建就可以了.我明白模板的功能如下:
template<typename VarT>
VarT get(std::string const& name) const;
Run Code Online (Sandbox Code Playgroud)
应该放在标题中,因为编译器将无法根据调用代码专门化模板,但在完全特化的情况下,它是类的实现,因此专用模板方法应该已经存在公共符号.有人可以对这个问题有所了解吗?
Joh*_*itb 11
您的分析是正确的 - 一个显式专用的函数模板,其具有使用显式值指定的任何模板参数,提供函数的完整定义.
如果已将.cpp包含显式特化定义的相应文件正确包含到项目中,则VC++不应引发链接器错误.但是,对于标准合规性,请注意,您必须在封闭类之外声明您的专业化.标准禁止在封闭类中声明显式特化(而其他编译器将拒绝您的代码).因此,更改头文件以声明这样的特化,而不是
class VariableManager
{
public:
template<typename VarT>
VarT get(std::string const& name) const
{
// Some code...
}
private:
std::map<std::string, boost::any> mVariables;
};
// This method supposed to be fully evaluated, linkable method.
template<>
std::string VariableManager::get<std::string>(std::string const& name) const;
Run Code Online (Sandbox Code Playgroud)
我还要注意,你不能get<std::string>在课堂内打电话.那是因为任何这样的调用都不会看到显式的特化声明,因此会尝试从模板定义中实例化该函数.标准使得此类代码格式错误,无需诊断.