C++ 将(某种元)函数应用于类型序列
我有一个功能:C++ 将(某种元)函数应用于类型序列,c++,c++14,template-meta-programming,map-function,C++,C++14,Template Meta Programming,Map Function,我有一个功能: template <typename T> std::string foo(); template std::string foo(); 您可以将其视为将类型作为输入并生成字符串 我也有一个参数包,或者一个元组,这对你来说更方便;假设是 using std::tuple<MyParameters...> my_types; 使用std::tuple my_类型; 现在,我想对包中或元组的类型定义中的每个类型T依次调用foo 我意识到我可能可以使用B
template <typename T> std::string foo();
template std::string foo();
您可以将其视为将类型作为输入并生成字符串
我也有一个参数包,或者一个元组,这对你来说更方便;假设是
using std::tuple<MyParameters...> my_types;
使用std::tuple my_类型;
现在,我想对包中或元组的类型定义中的每个类型T
依次调用foo
我意识到我可能可以使用Boost的MPL或Boost Hana之类的库来实现这一点,但我不想将所有这些都写入我的代码中,我想知道这样做的原理是否可以用简洁的语言“捕捉”到
注:
- 如果您能够提供一个与通用lambda而不是模板函数一起工作的答案,则可以获得额外的积分
- 答案必须是C++14,而不是C++17
bar
的方法进行工作,那么您可以编写foo()
在bar
中调用方法(例如,操作符()
),如下所示
template <typename T>
std::string foo ()
{ return bar<T>()(); }
模板
std::stringfoo()
{返回条();}
下面是一个完整的工作(我不知道“简洁”是否足够)示例;如果我没有错的话,这是C++11
#include <tuple>
#include <complex>
#include <iostream>
template <typename ...>
struct bar;
template <typename T0, typename ... Ts>
struct bar<T0, Ts...>
{
std::string operator() ()
{ return "type; " + bar<Ts...>()(); }
};
template <template <typename ...> class C,
typename ... Ts1, typename ... Ts2>
struct bar<C<Ts1...>, Ts2...>
{
std::string operator() ()
{ return "type container; " + bar<Ts1...>()() + bar<Ts2...>()(); }
};
template <>
struct bar<>
{ std::string operator() () { return {}; } };
template <typename T>
std::string foo ()
{ return bar<T>()(); }
int main ()
{
std::cout << foo<int>() << std::endl;
std::cout << foo<std::tuple<int, long, short, std::tuple<long, int>>>()
<< std::endl;
std::cout << foo<std::complex<double>>() << std::endl;
}
#包括
#包括
#包括
样板
结构杆;
样板
结构条
{
std::字符串运算符()
{return“type;”“+bar()();}
};
样板
结构条
{
std::字符串运算符()
{return“类型容器;”+bar()()+bar();}
};
样板
结构条
{std::string操作符(){return{};}};
样板
std::stringfoo()
{返回条();}
int main()
{
std::cout@T.C.的评论确定了这一点
#include <array>
#include <string>
#include <iostream>
template <typename T> std::string foo() {
return std::to_string(sizeof(T));
}
template <typename... Ts>
std::array<std::string, sizeof...(Ts)> multi_foo() {
return { foo<Ts>()... };
}
int main() {
auto size_strings = multi_foo<char, short, int, long, long long>();
for(const auto& s : size_strings) { std::cout << s << ' '; };
std::cout << std::endl;
}
在x86_64计算机上。std::string bar[]={foo()…};
?@T.C.:是的,事实上非常简单。将此发展为下面的答案。这似乎有点巴洛克风格……你能解释一下你的解决方案比@T.C.的好处吗?我将@T.C.发展为ann Any Any Any an Any Any?首先,我想我误解了你的问题:我知道你的意图是将某个东西称为foo()
;如果您的意向需求只是使用foo()
的另一个模板(但可变)函数……是的,您的解决方案(基于T.C.)简单得多。
1 2 4 8 8