在“模板”和函数声明之间使用:template <typename trait =“”>使用tr = base_trait <trait> void fn(tr :: type arg){...}

时间:2018-09-25 19:30:20

标签: c++ templates

是否可以在template关键字和函数声明(可能还有对象声明等)之间使用使用别名?

template<typename trait> 
using tr = base_trait<trait> 

void fn(tr::type arg) { // edit: typename has to be here?

} 

如果没有,我如何达到这种可读性?

我想出的变量并不完美:

template<typename trait>
struct base_trait : trait {
    using thetype = typename trait::thetype;
};


struct int_trait {
    using thetype = int;
};


/* the pretty version which doesn't compile */
template <typename trait>
using tr = base_trait<trait>. 

void fn(tr::thetype arg) {
    // tr::

}

fn<int_trait>(1);


/* ugly long arglist version which works */
template <typename trait>
void fn(typename base_trait<trait>::thetype arg1, typename base_trait<trait>::thetype arg2) {
    using tr = base_trait<trait>; 

    // tr:: 
}

fn<int_trait>(1);


/* another boilerplate version that still requires `typename` */
template <typename tr>
void fn(typename tr::thetype arg) {
    // typename tr::  

    // wait, I have to type and read typename everywhere... (unless I add `using boilerplateusing = tr; edit: this using should not help?)
}

template <typename trait>
using boilerplateusing = fn<base_trait<trait>>;

boilerplateusing<int_trait>(1);

1 个答案:

答案 0 :(得分:2)

只需添加另一个模板参数,该参数默认使用trait的type成员,例如

template<typename trait, typename arg_t = typename base_trait<trait>::thetype> 
void fn(arg_t arg) {

} 

或者如果您想保留特征类型,可以使用

template<typename trait, typename tr = base_trait<trait>> 
void fn(typename tr::thetype arg) {

}

或者您可以同时拥有

template<typename trait, 
         typename tr = base_trait<trait>,
         typename arg_t = typename tr::thetype> 
void fn(arg_t arg) {

}