[英]Autodetect return type of template function
I have a some classes with a function. 我有一些带有功能的类。 In all classes the function has the same name and argument type but different return type.
在所有类中,函数均具有相同的名称和参数类型,但返回类型不同。 I need a some template function which can automagically detect correct template substitution without angle brackets.
我需要一些模板功能,可以自动检测正确的模板替换而无需尖括号。
Test code to illustrate question: 测试代码来说明问题:
struct Float
{
static Float convert(int i)
{
return Float{static_cast<float>(i)};
}
float _f;
};
struct Int
{
static Int convert(int i)
{
return Int{i};
}
int _i;
};
template<typename T>
T convert(int i)
{
return T::convert(i);
}
int main()
{
Float f1 = convert<Float>(10);
Int i1 = convert<Int>(10);
// Float f2 = convert(10); compilation error
// Int i2 = convert(10); compilation error
return 0;
}
PS templates makes me crazy I want but can't understand them. PS模板让我发疯,但我无法理解它们。
Not sure if it's a perfect fit to your needs, but you may simulate what you want with a class and a templated conversion operator: 不知道它是否完全适合您的需求,但是您可以使用类和模板化转换运算符来模拟您想要的内容:
class convert {
int arg;
public:
convert(int arg) : arg(arg) {}
template<class T>
operator T() const {
return T::convert(arg);
}
};
Since template argument deduction works for templated conversion operators, you can write this: 由于模板参数推导适用于模板转换操作符,因此您可以这样编写:
Float f1 = convert(10);
Int i1 = convert(10);
Just like you want. 就像你想要的。
Why do you need the convert function? 为什么需要转换功能? You can use a single argument constructor to do the same job.
您可以使用单个参数构造函数来完成相同的工作。
struct Float
{
Float(int i)
{
_f = static_cast<float>(i);
}
float _f;
};
struct Int
{
Int(int i)
{
_i = static_cast<int>(i);
}
int _i;
};
int main()
{
Float f2 = 10;
Int i2 = 10;
return 0;
}
If you're worried about the implicit calls to the constructor you can make it explicit 如果您担心对构造函数的隐式调用,则可以使其显式
struct Float
{
explicit Float(int i)
{
_f = static_cast<float>(i);
}
float _f;
};
int main()
{
Float f2 = Float(10);
return 0;
}
The readability of the code is affected if the function with same name and the same type of input arguments can produce different return types. 如果具有相同名称和相同类型的输入参数的函数可以产生不同的返回类型,则代码的可读性会受到影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.