Using template typename in a nested function template

冷暖自知 提交于 2019-12-25 09:32:54

问题


Alright, I'm struggling with templates. In this question I learned, that it is not possible to pass a type specifier to a function at all, so my next approach is passing the type inside <>.

Imagine a function template foo<U>(), which is member function of a template class A. So if I create an Object A<T> a I can call a.foo<U>() with any type.

How do I have to write an equivalent function template so I can pass a and U like wrappedFoo<U>(a)?

IMPORTANT Needs to be C++98 compliant


回答1:


You might do the following:

template <typename U, typename T>
XXXX /* See below */
WrappedFoo(/*const*/ A<T>& a)
{
    return a.template foo<U>();
}

The hard part is the return type without decltype of C++11.

So if the return type really depends of parameters type, you can create a trait, something like:

template <typename U, typename T>
struct Ret
{
    typedef U type;
};

template <typename T> struct Ret<T, A<T> >
struct Ret
{
    typedef bool type;
};

And then replace XXXX by typename Ret<U, T>::type



来源:https://stackoverflow.com/questions/46364828/using-template-typename-in-a-nested-function-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!