将整数或类型作为模板参数传递?
Passing an integer or a type as a template parameter?
这是我正在尝试做的一个示例案例(这是一个"测试"案例,只是为了说明问题):
#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*/
?
这是我的做法,但我稍微改变了你的界面:
#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
的用途)。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>(...)
如果函数很小,我建议您使用重载。
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用指向成员的指针将成员函数作为参数传递
- 如何将参数传递给正在使用模板的类
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将部分流作为参数传递
- 我正在开发服务器,ip作为参数传递不起作用
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 将参数传递为"const"的奇怪效果
- 如何在 c++ 中将函数作为参数传递?
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 使用引用与指针将数组作为参数传递
- 将整数数组作为参数传递C++错误
- 将整数或类型作为模板参数传递?
- 在 C++ 中将整数数组作为参数传递
- 将指向函数的指针数组作为"int"参数传递是否可以将地址转换为整数?
- 将参数传递给方法时,初始化内联整数数组