这里是我想要做的情况为例(这是一个“测试”的情况下只是为了说明问题):传递一个整数或类型作为模板参数?
#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()
可以采取int
或std::ratio
作为第一个模板参数和调用f()
好的版本。
如何做到这一点,而不写两个g()
功能?换句话说,我必须写什么来代替/*An int OR a type*/
?
在您的编辑:为什么不命名您的'std :: ratio'参数并使用'r.num'和'r.den'? :) – Xeo
@Xeo:好的建议,谢谢!完成。 –
也许也解释了为什么你特别使用成员而不是'N'和'D',而不是只在编辑历史中使用它。 – Xeo