简体   繁体   中英

Template in a Macros in C++?

Is it possible to do so

# define abc<T1> __abc<T1, T2>

template<typename T2> void somefun() {
    ... 
    abc<int>(...);
    abc<double>(...);
    ...
}

Just to not write it every time i call abc

In C++11 you can do:

template<typename T2> void somefun() {
    template <typename T>
    using abc = __abc<T, T2>;
}

Without that you can use a macro but you'd need to do:

#define abc(T1) __abc<T1, T2>

//usage:

abc(Type) instance;

but since that doesn't look very natural I'd avoid it personally.

If you want to avoid the macro pre-C++11 you can do something like:

template <typename T2>
struct type {
  template <typename T1>
  struct lookup {
    typedef __abc<T1,T2> type;
  };
};

template <typename T2> void somefun() {
  typedef type<T2> abc;
  typename abc::template lookup<int>::type();
}

But in all honesty that's less readable than even the macro case

(Note: __abc is reserved)

Yes, but you need to use round parentheses.

# define abc(T1) __abc<T1, T2>

template<typename T2> void somefun() {
    ... 
    abc(int)(...);
    abc(double)(...);
}

Edit: My recommendation is not using macros for this kind of abbreviation at all. Use awoodlands solution or maybe a default template parameter. And thou shall not use reserved names.

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