【发布时间】:2012-11-04 17:18:22
【问题描述】:
这是我正在尝试做的一个示例案例(这是一个“测试”案例,只是为了说明问题):
#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*/?
【问题讨论】:
标签: c++ templates c++11 metaprogramming