[英]Issue with template in structs struct in c++
I have a struct in c++ which is something like this: 我在C ++中有一个结构,如下所示:
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: 我想做的是调用方法
myproc()
如下所示:
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
. 我知道这是因为编译器无法知道
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
. T
表示类型,例如int
。 Writing return T;
写作
return T;
will be the same as return int;
将与
return int;
相同return int;
when T
is an int
. 当
T
为int
。 Is return int;
return int;
valid? 有效?
You can call your function template as: dummy.myproc<int>();
您可以将函数模板调用为:
dummy.myproc<int>();
. 。 You have to tell it what
T
is by writing <int>
. 您必须通过编写
<int>
来告知T
是什么。 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. 但是,如果函数采用了
T
参数,则编译器将能够通过查看参数的类型来推断T
是什么。 For example dummy.myproc(2.3)
would resolve as T
being a double
because 2.3
is a double. 例如
dummy.myproc(2.3)
将解析为T
是double
dummy.myproc(2.3)
因为2.3
是双dummy.myproc(2.3)
。
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>()
. 但是,由于在
s.myproc()
的上下文中不可推导template参数, s.myproc()
您将不得不执行s.myproc<mytype>()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.