简体   繁体   English

专业模板类的模板构造函数

[英]Specializing Template Constructor Of Template Class

My brain has melted due to several weeks of 14-hour days. 由于数周的14小时工作日,我的大脑已经融化。

I have a template class, and I'm trying to write a template convert constructor for this class, and specialize that constructor. 我有一个模板类,我正在尝试为这个类编写一个模板转换构造函数,并专门构造该构造函数。 The compiler (MSVC9) is quite displeased with me. 编译器(MSVC9)对我很不满意。 This is a minimal example of actual code I'm trying to write. 这是我正在尝试编写的实际代码的最小示例。 The compiler error is inline with the code. 编译器错误与代码内联。

Help me unmelt my brain. 帮助我解开我的大脑。 What's the syntax I need here to do what I'm trying to do? 我需要在这里做什么才能做我想做的事情? NOTE: In my real code, I must define the convert constructor outside of the declaration, so that's not an option for me. 注意:在我的实际代码中,我必须在声明之外定义转换构造函数,因此这不是我的选项。

#include <string>
#include <sstream>
using namespace std;

template<typename A>
class Gizmo
{
public:
    Gizmo() : a_() {};
    Gizmo(const A& a) : a_(a) {};
    template<typename Conv> Gizmo(const Conv& conv) : a_(static_cast<A>(conv)) {};

private:
    A a_;
};

//
// ERROR HERE:
// " error C2039: 'Gizmo<B>' : is not a member of 'Gizmo<A>'"
//
template<> template<typename B> Gizmo<string>::Gizmo<typename B>(const B& b)
{
    stringstream ss;
    ss << b;
    ss >> a_;
}

int main()
{
    Gizmo<int> a_int;
    Gizmo<int> a_int2(123);
    Gizmo<string> a_f(546.0f);

    return 0;
}
template<> template<typename B> Gizmo<string>::Gizmo(const B& b)

另请注意, 必须删除const typename B&中的typename关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM