Template type deduction in function return type

孤街浪徒 提交于 2020-01-06 06:45:30

问题


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?


回答1:


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



回答2:


Try with

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

and the same for getVar1()



来源:https://stackoverflow.com/questions/47356284/template-type-deduction-in-function-return-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!