我有模板专业化的问题,我想了解.我正在使用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)
应该放在标题中,因为编译器将无法根据调用代码专门化模板,但在完全特化的情况下,它是类的实现,因此专用模板方法应该已经存在公共符号.有人可以对这个问题有所了解吗?
我有一个像这样的代码片段,在VC++ 2010下编译.
std::set<int> s1;
std::set<int> s2;
std::set<int> res_set;
std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), res_set.begin());
Run Code Online (Sandbox Code Playgroud)
据我所知,这应该有效.但是,我得到了构建错误:
c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm(4494): error C3892: 'std::_Tree_const_iterator<_Mytree>::operator *' : you cannot assign to a variable that is const
1> with
1> [
1> _Mytree=std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>
1> ]
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm(4522) : see reference to function template instantiation '_OutIt std::_Set_intersection<_InIt1,_InIt2,_OutIt>(_InIt1,_InIt1,_InIt2,_InIt2,_OutIt)' being compiled
1> with
1> [
1> _OutIt=std::_Tree_const_iterator<std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>>,
1> _InIt1=std::_Tree_unchecked_const_iterator<std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>>,
1> _InIt2=std::_Tree_unchecked_const_iterator<std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>>
1> ]
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm(4549) : …Run Code Online (Sandbox Code Playgroud)