简体   繁体   中英

Template type deduction in function return type

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?

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;
}

Try with

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

and the same for getVar1()

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