c ++中的结构体结构中的模板问题

Pun*_*tal 0 c++ templates struct

我在c ++中有一个结构,它是这样的:

struct mystruct {
  template <typename T>
  T myproc() {
    std::cout << "RETURNING T";
    return T();
  }
};
Run Code Online (Sandbox Code Playgroud)

现在这个结构已经存在(这只是精确结构的示例副本),我需要使用它.我想要做的是调用如下方法myproc():

    int _tmain(int argc, _TCHAR* argv[])
    {
      mystruct dummystruct;
      int y = dummystruct.myproc();
      return 0;
    }
Run Code Online (Sandbox Code Playgroud)

但它给了我这个编译错误:

    error C2783: 'T mystruct::myproc(void)' : could not deduce template argument for 'T'
    see declaration of 'mystruct::myproc'
Run Code Online (Sandbox Code Playgroud)

我知道是因为编译器无法知道是什么T.

所以我的问题是,结构中的函数声明是否合适?我不这么认为,但是这段代码已经存在于我们的一个旧代码中,所以我认为我应该得到别人的意见.

所以我知道这是错的,但如果有人认为它是正确的,请解释我如何使用它.

Dav*_*vid 5

T代表一种类型,例如int.写作return T;将是一样的return int;,当Tint.是否return int;有效?

您可以将您的功能模板调用为:dummy.myproc<int>();.你必须T通过写作来告诉它是什么<int>.但是,如果函数接受了一个T参数,那么编译器就可以T通过查看参数的类型来推断出是什么.例如dummy.myproc(2.3)将解决作为T是一个double,因为2.3是双.


Rap*_*ptz 5

我真的很惊讶编译(如果它最初?).

模板可以被认为是一种类型.你不会回来一个类型吗?

你的代码可以这样看.

struct mystruct {
  int myproc() {
    std::cout << "RETURNING INT";
    return int;
  }
};
Run Code Online (Sandbox Code Playgroud)

哪个不是很有效.

如果要返回默认构造值,则需要放置括号.

struct mystruct {
  template <typename T>
  T myproc() {
    std::cout << "RETURNING T";
    return T();
  }
};
Run Code Online (Sandbox Code Playgroud)

但是,由于模板参数在s.myproc()您不得不进行的上下文中是不可推断的s.myproc<mytype>().