简体   繁体   English

Template类非模板化方法参数

[英]Template class non-templated method argument

I have a class which uses templates. 我有一个使用模板的类。 It is something like this: 它是这样的:

template <typename T>
class a
{

public:
    a(T arg);
    a<T> func(a arg); // This seems to work, but...
    a<T> func(a<T> arg); // ...should I be doing this instead?

private:
    T local;
};

Notice the two function templates for func . 注意func的两个函数模板。 Both will compile (of course, not at the same time) but which one is correct, or does it not matter? 两者都会编译(当然,不是在同一时间),但哪一个是正确的,还是无关紧要? In the first, I have specified that class a is the argument... In this first case, can a different type be used in place of T... For example can I do this: 在第一个中,我已经指定class a是参数...在第一种情况下,可以使用不同的类型代替T ...例如,我可以这样做:

a<float> b;
a<int> c;
a<int> d;
d = c+ b;

I am guessing the answer is "no" because it doesn't compile! 我猜测答案是“不”,因为它不编译!

In the second case, it is clear that the argument must have the same type templated. 在第二种情况下,很明显参数必须具有相同的模板类型。

Due to what I discussed above, I am guessing the compiler actually interprets a<T> func(a arg); 由于我上面讨论过,我猜测编译器实际上解释a<T> func(a arg); as a<T> func(a<T> arg); 作为a<T> func(a<T> arg); . Am I correct? 我对么?

In your class template a means a<All the tempalte args here> ie a<T> 在你的类模板中, a表示a<All the tempalte args here>a<T>

So both your functions are same. 所以你的功能都是一样的。

If you want provide another type you should use template function 如果要提供其他类型,则应使用模板功能

template <typename T> {
class a {
    template<typename U>
    a<T> func(a<U> arg);
}

You may also consider return std::common_type<T, U>::type but in your case it'll not compile because common type for float and int is float 您也可以考虑返回std::common_type<T, U>::type但在您的情况下它不会编译,因为floatint常见类型是float

a<float> x = a<int>(1) + a<float>(8)

should work in that case 应该适用于那种情况

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

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