简体   繁体   中英

Issue with template in structs struct in c++

I have a struct in c++ which is something like this:

struct mystruct {
  template <typename T>
  T myproc() {
    std::cout << "RETURNING T";
    return T();
  }
};

Now this struct already exists(this is just a sample replica of exact struct) which I need to use. What I am trying to do is call the method myproc() like below:

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

But it gives me this compilation error:

    error C2783: 'T mystruct::myproc(void)' : could not deduce template argument for 'T'
    see declaration of 'mystruct::myproc'

which I know is because the compiler has no way to know what is T .

So my question is, is the function declaration in struct proper? I don't think so but this code already exists in one of our old code, so I thought I should get others opinion on it.

So I know it is wrong, but if someone thinks its correct, please explain me how to use it then.

T represents a type, such as int . Writing return T; will be the same as return int; when T is an int . Is return int; valid?

You can call your function template as: dummy.myproc<int>(); . You have to tell it what T is by writing <int> . If however the function took a T argument then the compiler would be able to deduce what T is by seeing the type of the argument. For example dummy.myproc(2.3) would resolve as T being a double because 2.3 is a double.

I'm actually surprised that compiled (if it did initially?).

A template can be thought of as a type. You wouldn't return a type would you?

Your code can be looked as this.

struct mystruct {
  int myproc() {
    std::cout << "RETURNING INT";
    return int;
  }
};

Which isn't very valid.

If you want to return the default constructed value you are going to need to put parentheses.

struct mystruct {
  template <typename T>
  T myproc() {
    std::cout << "RETURNING T";
    return T();
  }
};

However, since the template parameter isn't deducible in the context of s.myproc() you're going to have to do s.myproc<mytype>() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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