函数返回类型中的模板类型推导 [英] Template type deduction in function return type

查看:84
本文介绍了函数返回类型中的模板类型推导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在成员变量和函数参数的模板类型推论

我的.h文件包含以下几行。

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

.cpp文件具有以下代码。

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

现在,当我在g ++中使用C ++ 11支持编译代码时,

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
 ^

如何清除错误?

推荐答案

编译器无法知道 T0 是在 MyClass< T> 。因此,您需要适当地限定reutrn类型:

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

这篇关于函数返回类型中的模板类型推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆