c ++ template class method returns a value type is typedef out, or auto, then how to define this method outside of class?

c ++ template class method returns a value type is typedef out, or auto, then how to define this method outside of class?

  • For example, the method of the return value is defined max1 out with typedef mint, then how to define this outside the class it?
template<typename T>
struct aa{

  typedef int mint;

  mint max1(T a);

  auto max2(T a) -> decltype(int(1));
  mint data;
};

Try 1:

template<typename T>
mint aa<T>::max1(T a){}

The results of attempts to 1: Compile however, does not recognize mint tips

Try 2:

template<typename T>
aa<T>::mint aa<T>::max1(T a){}

The results try 2: Still not compile

Try 3: preceded by typename keyword

template<typename T>
typename aa<T>::mint aa<T>::max1(T a){}

Try 3 results: compiled by

  • For example, the method max2 return value is auto, then how to define this outside the class it?

    Use decltype (c ++ 11 properties). Let decltype to push to the type of auto

template<typename T>
struct aa{

  typedef int mint;

  mint max1(T a);

  auto max2(T a) -> decltype(int(1));
  mint data;
};

template<typename T>
typename aa<T>::mint aa<T>::max1(T a){
  
}

template<typename T>
auto aa<T>::max2(T a) -> decltype(int(1)){
  return a;
}

int main(){
  aa<int> a;
  auto x = a.max2(12);

  std::cout << x << std::endl;
}
  • decltype place is the most widely used in conjunction with auto generic programming, for the return type of the function to track

    Such a method has a lower, there are two template parameters Tx and Ty, the return value to the addition of two types of objects and template parameter. This case, the return value of this function is to write it Tx, Ty or write it? Write what will not work, it must be decltype (_Tx + Ty) to be pushed out.

    template <typename _Tx, typename _Ty>
    auto add(_Tx x, _Ty y)->decltype(_Tx*_Ty)
    {
        return x*y;
    }

decltype Reference: https://www.cnblogs.com/QG-whz/p/4952980.html

c / c ++ mutual learning QQ group: 877 684 253

I micro letter: xiaoshitou5854

Guess you like

Origin www.cnblogs.com/xiaoshiwang/p/11845696.html