Template type deduction in function return type

2019-08-23 03:17发布

This is in continuation with the question posted at Template type deduction for member variables and function arguments

My .h file contains the following lines.

#include <iostream>
#include <complex>
#include <typeinfo>


template <typename T>
class MyClass
 {


 template <typename T0>
struct myTypeTraits
 { using type = T0; };

template <typename T0>
struct myTypeTraits<std::complex<T0>>
 { using type = T0; };


public:

   using T0 = typename myTypeTraits<T>::type;

   void setVar1(const T0& v);

   void setVar2(const T& v);

 T0 getVar1() const;
T getVar2() const;




   void print() const;

   T0 var1;
   T  var2;
 };

The .cpp file has the following codes.

#include "tmp.h"
template <class T>
void MyClass<T>::setVar1(const T0& v)
{
    var1 = v;
}


template <class T>
void MyClass<T>::setVar2(const T& v)
{
    var2 = v;
}


template <class T>
T0 MyClass<T>::getVar1() const
{
    return var1;
}


template <class T>
T MyClass<T>::getVar2() const
{
    return var2;
}


template <typename T>
void MyClass<T>::print() const
{
    std::cout<<"var1: "<<var1<<std::endl;
    std::cout<<"var2: "<<var2<<std::endl;

}



int main()
{

    MyClass<float> tmp;

    MyClass<std::complex<float> > tmp1;

    tmp.print();
    tmp1.print();
    return 0;
}

Now when I compile the code using C++ 11 support in g++, I get the following error.

tmp.cpp:17:1: error: ‘T0’ does not name a type
 T0 MyClass<T>::getVar1() const
 ^

How can I remove the error?

2条回答
Juvenile、少年°
2楼-- · 2019-08-23 03:56

Try with

// ......................vvvvvvvvvvvvvvvvvvvvvvv
void MyClass<T>::setVar1(typename MyClass<T>::T0 const & v)
{
    var1 = v;
}

and the same for getVar1()

查看更多
Melony?
3楼-- · 2019-08-23 03:58

The compiler can't know that T0 is defined in MyClass<T>. So you need to properly qualify the reutrn type:

template <class T>
typename MyClass<T>::T0 MyClass<T>::getVar1() const {
  return var1;
}

Alternatively, you can use a trailing return type, which you won't need to qualify either:

template <class T>
auto MyClass<T>::getVar1() const -> T0 {
  return var1;
}
查看更多
登录 后发表回答