一个可变参数模板方法接受给定数量的双精度? [英] A variadic template method to accept a given number of doubles?
本文介绍了一个可变参数模板方法接受给定数量的双精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
template <unsigned int N> class myclass
{
public:
template <typename... Args> void mymethod(Args... args)
{
// Do interesting stuff
}
};
我想要 mymethod
正好N倍。那可能吗?也就是说,我有:
I want mymethod
to be called only with exactly N doubles. Is that possible? That is, say that I have:
myclass <3> x;
x.mymethod(3., 4., 5.); // This works
x.mymethod('q', 1., 7.); // This doesn't work
x.mymethod(1., 2.); // This doesn't work
如何完成这项工作?
推荐答案
对于参数数量约束你可以很容易地检查 sizeof ...(Args)== N
但是为了检查所有的参数是否为双精度型,你需要建立一个递归类型trait来检查每个参数的 std :: is_same
。
For the number of arguments constraint you can easily check if sizeof...(Args) == N
but for checking if all the arguments are doubles you need to build a recursive type trait that checks std::is_same
for each of the arguments.
template<typename...>
struct are_same : std::true_type
{};
template<typename T>
struct are_same<T> : std::true_type
{};
template<typename T, typename U, typename... Types>
struct are_same<T, U, Types...> :
std::integral_constant<bool, (std::is_same<T, U>::value && are_same<T, Types...>::value)>
{};
注意首先声明are_same
然后在方法中使用 std :: enable_if
利用 SFINAE 。
Then just implement the constraint in your method return type using std::enable_if
by taking advantage of SFINAE.
template <unsigned int N> class myclass
{
public:
template <typename... Args>
typename std::enable_if<(are_same<double, Args...>::value && sizeof...(Args) == N), void>::type
/* void */ mymethod(Args... args)
{
// Do interesting stuff
}
};
这篇关于一个可变参数模板方法接受给定数量的双精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文