6

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

4

2 回答 2

12

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)

于 2012-05-10T09:51:37.407 回答
2

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.

于 2012-05-10T10:37:08.870 回答