문제

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. 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:

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); as a<T> func(a<T> arg);. Am I correct?

도움이 되었습니까?

해결책

In your class template a means a<All the tempalte args here> i.e 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

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

should work in that case

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top