模板特化乘以定义的符号 [英] template specialization multiply defined symbols

查看:140
本文介绍了模板特化乘以定义的符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我在这里很容易遗漏一些东西,但我有一个我专门的类的模板成员函数。

I know i'm missing something easy here but I've got a templated member function of a class which I've specialised.

MyClass
{
    template<typename T> T GetTFromVariable(shared_ptr<TOtSimpleVariable> v, string s);
}

template<typename T>
T MyClass::GetTFromVariable(shared_ptr<TOtSimpleVariable> v, string s)
{
    throw std::runtime_error("Don't know how to convert " + ToString(v->GetString()));
}

template<>
int MyClass::GetTFromVariable<int>(shared_ptr<TOtSimpleVariable> v, string s)
{
    return v->GetInteger();
}

template<>
string MyClass::GetTFromVariable<string>(shared_ptr<TOtSimpleVariable> v, string s)
{
    return v->GetString();
}

// etc for other specialisations.

这是在我的头文件中定义的(模板应该是),但是当我去编译一个代表这种错误的代表是:

This is defined in my header file (as templates should be) but when I go and compile I get a bunch of mutliply defined symbols, a representative such error is:

     OtCustomZenith_logic.lib(PtPathOutput.obj) : error LNK2005: "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall MyClass::GetTFromVariable<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >(class boost::shared_ptr<class TOtSimpleVariable>,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (??$GetTFromVariable@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@CommandProperties@@QAE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$shared_ptr@VTOtSimpleVariable@@@boost@@V12@@Z) already defined in TableFareSystem_test.obj

我可以通过内联方法来修复它,但我不认为应该有必要...我忘记了什么?

I can fix it by inlining the methods but I don't think that should be necessary... what did I forget?

编辑:我使用的是Visual Studio 2010

I'm using Visual Studio 2010

推荐答案

Alf指出,完全专业化不再是模板。
然而,我不确定是否已经内联定义
您也应该能够拆分声明和定义。

As Alf noted, the full specialization is no longer a template. However, I am not sure it has to be defined inline. You should also be able to split the declaration and definition.

在标题中有:

template<> 
int MyClass::GetTFromVariable<int>(shared_ptr<TOtSimpleVariable> v, string s);

并且在实施中有:

template<>
int MyClass::GetTFromVariable<int>(shared_ptr<TOtSimpleVariable> v, string s)
{
    return v->GetInteger();
}

我也认为根据权利,模板定义也应该显式地> inline (我总是这样做),但如果一个给定的编译器在应用模板的ODR时不轻松,就不会感到太惊讶了。我有兴趣看到另外说明的标准参考。

I also had thought that by rights the templated definition should also be explicitly inline (I always have done so) but would not be too surprised if a given compiler was lax in applying the ODR for templates. I'd be interested to see the standard reference that states otherwise.

这篇关于模板特化乘以定义的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆