是否有一种方法来声明模板化函数的类型名称? [英] Is There a Way to Declare a typename for a Templatized Function?
问题描述
所以,我有这种模板化的功能(我知道这很难看。)
So, I have this templatized function (which I know is ugly to look at.)
我的意图是不默认模板参数,我的目的是创建一个 typename
派生自 T
My intention was not to default the template parameter though, my intention was to create a typename
derived from T
that could be used in caster
that the user could not assign to.
我可以在 caster
问题是如何为用户不能作为参数传递的模板化函数创建 typename
?
My question is how do I create a typename
for a templatized function which the user cannot pass as an argument?
例如:
template <typename T>
typename R = std::conditional<sizeof(T) == 4, char, short>;
R foo(T bar){return R(bar);}
不编译,但这是我想完成的行为。
Clearly this code doesn't compile, but that's the behavior I'd like to accomplish. Is a functor the only way to do this?
推荐答案
在C ++ 14中,这是一个使用返回类型推导优化解决的方法。
In C++14, this is elegantly solved using return type deduction.
// C++14
#include <type_traits>
template <typename T>
decltype(auto)
foo(T bar)
{
using R = std::conditional_t<sizeof(T) == 4, char, short>;
return static_cast<R>(bar);
}
在C ++ 11中,您必须重复类型计算。
In C++11, you'd have to repeat the type computation.
// C++11
#include <type_traits>
template <typename T>
typename std::conditional<sizeof(T) == 4, char, short>::type
foo(T bar)
{
using R = typename std::conditional<sizeof(T) == 4, char, short>::type;
return static_cast<R>(bar);
}
使用 decltype
找出类型。
// C++11
#include <type_traits>
template <typename T>
typename std::conditional<sizeof(T) == 4, char, short>::type
foo(T bar)
{
using R = decltype(foo(bar));
return static_cast<R>(bar);
}
但是坦率地说,使用简单的默认类型参数有什么问题? p>
But frankly, what is wrong with using a simple default type parameter?
// C++11
#include <type_traits>
template <typename T,
typename R = typename std::conditional<sizeof(T) == 4, char, short>::type>
R
foo(T bar)
{
return static_cast<R>(bar);
}
注意,我已经替换了 R在
你确定这是你想要的吗? return
语句中使用 static_cast
来隐藏编译器关于缩小转换的警告,
Note that I have replaced the value initialization of R
in your return
statement with a static_cast
to silence the compiler warning about the narrowing conversion. Are you sure that this is what you want, though?
这篇关于是否有一种方法来声明模板化函数的类型名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!