【问题标题】:What have I done wrong with this simple template class?这个简单的模板类我做错了什么?
【发布时间】:2010-11-15 05:27:49
【问题描述】:

我编写了一个小类来帮助与 MSVC 的笨重类型进行转换:

template <class FromType>
struct convert
{
    convert(FromType const &from)
        :   from_(from) {}
    operator LARGE_INTEGER() {
        LARGE_INTEGER li;
        li.QuadPart = from_;
        return li;
    }
private:
    FromType const &from_;
};

稍后我会这样做:

convert(0)

并从 MSVC 获取此错误消息:

1>e:\src\cpfs\libcpfs\device.cc(41): error C2955: 'convert' : 使用类模板需要模板参数列表

1> e:\src\cpfs\libcpfs\device.cc(17) : 见“convert”声明

我认为FromType 可以从我传递的整数中推断出来?怎么回事?

【问题讨论】:

  • 你需要做这样的事情 convert(0)

标签: c++ visual-studio templates


【解决方案1】:

类模板永远不会被隐式实例化。鉴于您给出的类定义,您必须说:

convert<int>(0)

...调用该类的构造函数。

使用默认模板参数,您可以改进(?)它:

template <class FromType = int>
struct convert
{ /* ... */ };

然后调用它:

convert<>(0)

...但恐怕这是您使用类模板所能做的最好的事情。您可能希望使用为您实例化类对象的函数模板:

template <typename FromType>
convert<FromType> make_convert(FromType from) {
   return convert<FromType>(from);
}

例如,这或多或少是在 std::make_pair() 中使用的方法。

【讨论】:

  • 谢谢。我选择了一个转换工厂和转换器类。后来我把它们扔了出去,手动做了,但是嗯:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-22
  • 2016-03-08
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多