将整数或类型作为模板参数传递?

Passing an integer or a type as a template parameter?

本文关键字:参数传递 整数 类型      更新时间:2023-10-16

这是我正在尝试做的一个示例案例(这是一个"测试"案例,只是为了说明问题):

#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。问题如下:

我想通过g()"包装"这个函数,它可以将intstd::ratio作为第一个模板参数并调用f()的良好版本。

如何在不编写两个g()函数的情况下做到这一点?换句话说,我必须写什么而不是/*An int OR a type*/

这是我的做法,但我稍微改变了你的界面:

#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

笔记:

  1. 我利用了constexpr不通过模板参数传递编译时常量(这就是constexpr的用途)。

  2. g现在只是一个完美的货运代理。 但是我无法使用std::forward,因为它没有用constexpr标记(可以说是 C++11 中的缺陷)。 所以我放弃使用static_cast<T&&>。 完美的转发在这里有点矫枉过正。 但这是一个很好的成语,需要彻底熟悉。

如何在不编写两个 g() 函数的情况下做到这一点?

你没有。C++无法采用某种类型的类型或值,除非通过重载。

模板参数不可能同时采用类型和非类型值。

解决方案 1:

重载函数。

解决方案 2:

可以将值存储在类型中。前任:

template<int n>
struct store_int
{
static const int num = n;
static const int den = 1;
};
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<typename Something, typename Type>
constexpr Type g(const Type x)
{
return f<Something, Type>(x);
}

但是使用此解决方案,您必须指定g<store_int<42> >(...)而不是g<42>(...)

如果函数很小,我建议您使用重载。