C++ 混合了经典名称重载的模板元编程
我想让一个简单的函数一次应用到多个变量模板中,它工作得很好,但我觉得不够满意。以下是工作代码:C++ 混合了经典名称重载的模板元编程,c++,c++11,overloading,variadic-templates,variadic-functions,C++,C++11,Overloading,Variadic Templates,Variadic Functions,我想让一个简单的函数一次应用到多个变量模板中,它工作得很好,但我觉得不够满意。以下是工作代码: #include <iostream> // generated for last (or the only) variable sent to apply_to_many template overload template<class Fun, class Type> void apply_to_many(Fun fun, Type& current) {
#include <iostream>
// generated for last (or the only) variable sent to apply_to_many template overload
template<class Fun, class Type>
void apply_to_many(Fun fun, Type& current)
{
current = fun(current);
}
// variadic template + variadic arguments, fun is applied to
// current variable, and template is generated for the rest
template<class Fun, class Type, class ...Types>
void apply_to_many(Fun fun, Type& current, Types&... other_variables)
{
current = fun(current);
if(sizeof...(other_variables) > 0)
apply_to_many(fun, other_variables...);
}
// simple function returning square of value
int square(int x)
{
return x*x;
}
int main()
{
// some ints
int a{3}, b{4}, c{5}, d{6}, e{7};
std::cout << a << '\t'
<< b << '\t'
<< c << '\t'
<< d << '\t'
<< e << std::endl;
apply_to_many(square, a, b, c, d, e);
std::cout << a << '\t'
<< b << '\t'
<< c << '\t'
<< d << '\t'
<< e << std::endl;
}
虽然a b c d e
可以是不同的类型,如int
,double
,complex
,但这里应用的函数仅用于int
s,因此int
s与int
s类似,而float
s与int
s类似,complex
es的平方与int
s类似。。。哦,complex
就是无法转换。要点是-最好使用为这些类型提供的经典重载,如std::sqrt
或std::pow
。但显然,我们不能在不显式选择一个重载的情况下将重载名称传递给模板
apply_to_many(std::sqrt, a, b, c, d, e); //error
据我所知,我们不能将模板函数作为参数发送(这会令人惊讶,但可能很棘手)。我会接受任何东西,即使是宏。您可以使用通用lambda(C++14): 在c++11中,必须使用旧方法创建函子:
struct Sqrt
{
template <typename T>
auto operator()(T value) const
-> decltype(std::sqrt(value))
{
return std::sqrt(value);
}
};
您可以使用通用lambda(C++14): 在c++11中,必须使用旧方法创建函子:
struct Sqrt
{
template <typename T>
auto operator()(T value) const
-> decltype(std::sqrt(value))
{
return std::sqrt(value);
}
};
struct Sqrt
{
template <typename T>
auto operator()(T value) const
-> decltype(std::sqrt(value))
{
return std::sqrt(value);
}
};
apply_to_many(Sqrt{}, a, b, c, d, e);