我正在编写一种"异步工厂",其中耗时的具体对象构造被推迟到std::async任务中.每个AsyncFactory都会存储一个指向对象的智能指针.
[这不是Factory Pattern最正确的应用,但它是为了MWE].
#include <future>
#include <memory>
#include <type_traits>
#include <cassert>
/**
* @param I is the interface type
* @param Ptr is the memory handler. Default = unique; optional = shared
*/
template <class I, template<class> class Ptr = std::unique_ptr>
class AsyncFactory
{
/**
* @param C - the concrete type for the interface I
* @param Ts - the variadic params
*/
template <class C, typename... Ts>
void _future_reload(Ts&&... params) …Run Code Online (Sandbox Code Playgroud) 让我深入研究C++ 14泛型lambdas:
#include <iostream>
// g++ -std=c++14
template<typename T>
T incr(T v)
{
return v + 1;
}
int main()
{
float f = 2.0;
int i = 3;
auto selfincr = [] (auto & value)
{
value = incr<std::remove_reference<decltype(value)>>(value); // A
value = incr<decltype(value)>(value); // B
};
selfincr(f);
selfincr(i);
std::cout << "f " << f << ", i " << i << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
因为线// B引起了
从'T'类型的右值开始无效初始化'T&'类型的非const引用
我的直接猜测是删除了引用,所以我添加了一行// A.但这会产生一个
调用'incr(T&)'没有匹配函数
那我怎么能删除那个引用呢?
按照 Scott Meyer 的“现代 C++”中的示例,我将利用std::array模板进行大小推导。我在尝试编译我的myUsage函数用法时遇到了困难。
#include <array>
#include <iostream>
template <typename T, std::size_t N>
constexpr std::size_t arraySize(T (&) [N]) noexcept
{
return N;
}
void scottUsage()
{
int b[5];
std::array<short, arraySize(b)> c;
std::cout << arraySize(b) << " = " << c.size() << "\n";
}
template <typename T, std::size_t N>
void myUsage(T & arr [N])
{
for (auto i=0; i<arraySize(arr); i++)
std::cout << arr[i] << "\t";
}
int main()
{
scottUsage();
int a[7];
myUsage(a);
}
Run Code Online (Sandbox Code Playgroud)
于是出现了两个问题:
在我的应用程序启动中,3-ary指针结构的内存分配很少.
#define N_1 1024
#define N_2 32
#define N_3 1024
#include <boost/date_time/posix_time/posix_time.hpp>
typedef uint16_t counts;
typedef counts * spectra;
typedef spectra * line;
typedef line * pline;
typedef pline * cube;
void foo()
{
cube cb = new pline[N_3];
for (int n3 = 0; n3 < N_3; n3++)
{
boost::posix_time::ptime tic = boost::posix_time::microsec_clock::local_time();
line ln = new spectra[N_2];
for (int n2 = 0; n2 < N_2; n2++)
{
ln[n2] = new counts[N_1]();
}
cb[n3] = &(ln);
boost::posix_time::ptime toc = boost::posix_time::microsec_clock::local_time(); …Run Code Online (Sandbox Code Playgroud)