将整数或类型作为模板参数传递? [英] Passing an integer or a type as a template parameter?
问题描述
这是我正在尝试做的一个示例案例(这是一个测试"案例,只是为了说明问题):
Here is an example case of what I'm trying to do (it is a "test" case just to illustrate the problem) :
#include <iostream>
#include <type_traits>
#include <ratio>
template<int Int, typename Type>
constexpr Type f(const Type x)
{
return Int*x;
}
template<class Ratio, typename Type,
class = typename std::enable_if<Ratio::den != 0>::type>
constexpr Type f(const Type x)
{
return (x*Ratio::num)/Ratio::den;
}
template</*An int OR a type*/ Something, typename Type>
constexpr Type g(const Type x)
{
return f<Something, Type>(x);
}
int main()
{
std::cout<<f<1>(42.)<<std::endl;
std::cout<<f<std::kilo>(42.)<<std::endl;
}
如您所见,f()
函数有两个版本:第一个版本采用 int
作为模板参数,第二个采用一个std::ratio
.问题如下:
As you can see, there are two versions of the f()
function : the first one takes an int
as a template parameter, and the second one takes a std::ratio
. The problem is the following :
我想通过 g()
来包装"这个函数,它可以将 int
或 std::ratio
作为第一个模板参数并调用 f()
的好版本.
I would like to "wrap" this function through g()
which can take an int
OR a std::ratio
as first template parameter and call the good version of f()
.
如何在不编写两个 g()
函数的情况下做到这一点?换句话说,我必须写什么来代替 /*An int OR a type*/
?
How to do that without writing two g()
functions ? In other words, what do I have to write instead of /*An int OR a type*/
?
推荐答案
这是我的方法,但我对你的界面做了一些改动:
Here's how I would do it, but I've changed your interface slightly:
#include <iostream>
#include <type_traits>
#include <ratio>
template <typename Type>
constexpr
Type
f(int Int, Type x)
{
return Int*x;
}
template <std::intmax_t N, std::intmax_t D, typename Type>
constexpr
Type
f(std::ratio<N, D> r, Type x)
{
// Note use of r.num and r.den instead of N and D leads to
// less probability of overflow. For example if N == 8
// and D == 12, then r.num == 2 and r.den == 3 because
// ratio reduces the fraction to lowest terms.
return x*r.num/r.den;
}
template <class T, class U>
constexpr
typename std::remove_reference<U>::type
g(T&& t, U&& u)
{
return f(static_cast<T&&>(t), static_cast<U&&>(u));
}
int main()
{
constexpr auto h = g(1, 42.);
constexpr auto i = g(std::kilo(), 42.);
std::cout<< h << std::endl;
std::cout<< i << std::endl;
}
42
42000
注意事项:
我已经利用
constexpr
不 通过模板参数传递编译时常量(这就是constexpr
).
I've taken advantage of
constexpr
to not pass compile-time constants via template parameters (that's whatconstexpr
is for).
g
现在只是一个完美的转发器.但是我无法使用 std::forward
因为它没有用 constexpr
标记(可以说是 C++11 中的一个缺陷).所以我选择使用 static_cast
g
is now just a perfect forwarder. However I was unable to use std::forward
because it isn't marked up with constexpr
(arguably a defect in C++11). So I dropped down to use static_cast<T&&>
instead. Perfect forwarding is a little bit overkill here. But it is a good idiom to be thoroughly familiar with.
这篇关于将整数或类型作为模板参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!