成员变量和函数参数的模板类型推导 [英] Template type deduction for member variables and function arguments
问题描述
考虑以下模板类的实现:
Consider the following implementation of a template class:
template<class T>
class MyClass
{
public:
void setVar1(const T& v1)
{
var1 = v1;
}
void setVar2(const T1& v2)
{
var2 = v2;
}
T var1;
T1 var2;
};
如果模板参数 T
是基本类型(例如 float
, double
或 long double
)我想要 T1 = T
.
If the template parameter T
is a fundamental type (like float
, double
, or long double
) I would like to have T1 = T
.
如果模板参数 T
是 std :: complex< float>
,我想使用 T = std :: complex< float>
和 T1 = float
.对于 std :: complex< double>
和 std :: complex< long double>
.
If the template parameter T
is std::complex<float>
, I would like to have T=std::complex<float>
and T1 = float
. Similarly for std::complex<double>
and std::complex<long double>
.
但是,在这种情况下,其他成员函数会阻止使用其解决方案.
However, the additional member functions prevents usage of their solution in this context.
推荐答案
Based on Bo Personns comment and the answer provided at https://stackoverflow.com/questions/47334675/template-type-derivation
我有以下工作示例.
.h文件的内容如下.
The content of my .h file is as follows.
#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);
T getVar2() const;
void print() const;
T0 var1;
T var2;
};
.cpp文件包含以下代码行.
The .cpp file contains the following lines of code.
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>
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;
}
上面的代码按预期工作.
The above code works as intended.
但是,我在函数返回中的模板类型推导中发布了另一个相关问题输入
这篇关于成员变量和函数参数的模板类型推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!