我想实例化一个可变模板类 Store<TArgs...>有一个std::vector对于 TArgs... 中的每种类型打包。
template<typename... TArgs> class Store {
// obviously not valid code
// assuming each type of TArgs... has a `unsigned int` id that can be
// retrieved with getId<T>()
std::array<sizeof...(TArgs), std::vector<TArgs...>> bags;
template<typename T> void add(T mValue) {
bags[getId<T>()].push_back(mValue);
}
template<typename T> std::vector<T>& get() {
return bags[getId<T>()];
}
};
假设我有一个 Store<int, float, double> .我显然知道,在编译时,它将能够存储 int , float和 double值(value)观。
我可以使用模板特化:
template<> class Store<int, float, double> {
std::vector<int> vi;
std::vector<float> vf;
std::vector<double> vd;
template<typename T> void add(T);
template<> void add<int>(int mValue) { vi.push_back(mValue); }
template<> void add<float>(float mValue) { vf.push_back(mValue); }
template<> void add<double>(double mValue) { vd.push_back(mValue); }
// ...
};
...但这需要手写所有可能的类型组合,并且不适用于用户定义的类型。
我相信编译器知道生成像 Store<int, float, double> 这样的类所需的一切使用可变参数模板 - 有没有办法真正表达这种意图?
最佳答案
下面应该做你想做的:
#include <type_traits>
#include <vector>
#include <tuple>
#include <iostream>
// indices are a classic
template< std::size_t... Ns >
struct indices
{
using next = indices< Ns..., sizeof...( Ns ) >;
};
template< std::size_t N >
struct make_indices
{
using type = typename make_indices< N - 1 >::type::next;
};
template<>
struct make_indices< 0 >
{
using type = indices<>;
};
// we need something to find a type's index within a list of types
template<typename T, typename U, std::size_t=0>
struct index {};
template<typename T, typename... Us, std::size_t N>
struct index<T,std::tuple<T,Us...>,N>
: std::integral_constant<std::size_t, N> {};
template<typename T, typename U, typename... Us, std::size_t N>
struct index<T,std::tuple<U,Us...>,N>
: index<T,std::tuple<Us...>,N+1> {};
// we need a way to remove duplicate types from a list of types
template<typename T,typename I=void> struct unique;
// step 1: generate indices
template<typename... Ts>
struct unique< std::tuple<Ts...>, void >
: unique< std::tuple<Ts...>, typename make_indices<sizeof...(Ts)>::type >
{
};
// step 2: remove duplicates. Note: No recursion here!
template<typename... Ts, std::size_t... Is>
struct unique< std::tuple<Ts...>, indices<Is...> >
{
using type = decltype( std::tuple_cat( std::declval<
typename std::conditional<index<Ts,std::tuple<Ts...>>::value==Is,std::tuple<Ts>,std::tuple<>>::type
>()... ) );
};
// a helper to turn Ts... into std::vector<Ts>...
template<typename> struct vectorize;
template<typename... Ts>
struct vectorize<std::tuple<Ts...>>
{
using type = std::tuple< std::vector<Ts>... >;
};
// now you can easily use it to define your Store
template<typename... Ts> class Store
{
using Storage = typename vectorize<typename unique<std::tuple<Ts...>>::type>::type;
Storage storage;
template<typename T>
decltype(std::get<index<T,typename unique<std::tuple<Ts...>>::type>::value>(storage))
slot()
{
return std::get<index<T,typename unique<std::tuple<Ts...>>::type>::value>(storage);
}
public:
template<typename T> void add(T mValue) {
slot<T>().push_back(mValue);
}
template<typename T> std::vector<T>& get() {
return slot<T>();
}
};
int main()
{
Store<int,int,double,int,double> store;
store.add(42);
store.add(3.1415);
store.add(21);
std::cout << store.get<int>().size() << std::endl;
std::cout << store.get<double>().size() << std::endl;
}
Live example (没有评论)
关于c++ - 可变参数模板类参数容器实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19463710/
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
我正在使用puppet为ruby程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这
我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击
在我的应用程序中,我需要能够找到所有数字子字符串,然后扫描每个子字符串,找到第一个匹配范围(例如5到15之间)的子字符串,并将该实例替换为另一个字符串“X”。我的测试字符串s="1foo100bar10gee1"我的初始模式是1个或多个数字的任何字符串,例如,re=Regexp.new(/\d+/)matches=s.scan(re)给出["1","100","10","1"]如果我想用“X”替换第N个匹配项,并且只替换第N个匹配项,我该怎么做?例如,如果我想替换第三个匹配项“10”(匹配项[2]),我不能只说s[matches[2]]="X"因为它做了两次替换“1fooX0barXg
我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere
我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option
我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano