这个示例代码:
#include <string>
#include <iostream>
template <int i>
struct Wrapper
{
static const std::string _str;
typedef const Wrapper<i+1> NextType_t; // template recursion
static NextType_t _nxt;
typedef const Wrapper<i-1> PrevType_t; // template recursion
static PrevType_t _prev;
};
template<int i>
const std::string Wrapper<i>::_str = std::to_string(i);
template<int i>
typename Wrapper<i>::NextType_t Wrapper<i>::_nxt;
template<int i>
typename Wrapper<i>::PrevType_t Wrapper<i>::_prev;
// recursion termination - lower bound
template <>
struct Wrapper<-1>
{
static const std::string _str;
typedef const Wrapper<0> NextType_t;
static NextType_t _nxt;
typedef const Wrapper<-1> PrevType_t;
static …Run Code Online (Sandbox Code Playgroud) 有人告诉我,如果有人删除原始文件, mmap() 可能会遇到麻烦。我想知道这是否真的发生了。所以我创建了一些小测试程序。我正在使用 linux。
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main(int, char**)
{
char const * const fileName = "/tmp/demo-file.dat";
size_t size;
{
struct stat st;
stat(fileName, &st);
size = st.st_size;
}
int fd = open(fileName, O_RDWR);
if (fd == -1)
{
std::cout << "open() failed, errno = " << errno << ":" << strerror(errno) << std::endl;
return (-1);
}
else
{
std::cout << "open() done (ok)" …Run Code Online (Sandbox Code Playgroud) 这是一个后续问题:
c++11 专用的“代理构造函数”委托给私有通用引用构造函数?
我想摆脱那里使用的“枚举类虚拟”。
但我无法委托给模板构造函数。
请参阅下面的代码示例。
#include <iostream>
#include <string>
#include <typeinfo>
class MyClass
{
private:
template <class T>
MyClass(T&& data)
: _data(std::forward<T>(data))
{
std::cout << "MyClass universal reference template c'tor" << std::endl;
}
public:
// proxy c'tors delegating to universal reference c'tor
MyClass (std::string const & data)
: MyClass<std::string>(data)
{
std::cout << "MyClass lvalue c'tor" << std::endl;
}
MyClass (std::string && data)
: MyClass<std::string>(std::move(data))
{
std::cout << "MyClass rvalue c'tor" << std::endl;
}
private:
std::string _data;
};
int
main( …Run Code Online (Sandbox Code Playgroud) 重新分解遗留代码我想合并彼此相关的单独模板类/结构(以避免名称空间污染).
Nested(下面)是一个帮助类MyStruct,我想进入 MyStruct.
但我无法做到这一点:
#include <type_traits>
#include <iostream>
struct YES {} ;
struct NO {};
template <typename TYPE>
struct MyStruct
{
template <typename TYPE_AGAIN = TYPE, typename SELECTOR = NO>
struct Nested
{
static void Print(void)
{
std::cout << "MyStruct::Nested<bool = false>::Print()" << std::endl;
}
};
template <>
struct Nested<TYPE, typename std::enable_if<std::is_integral<TYPE>::value, YES>::type>
{
static void Print(void)
{
std::cout << "MyStruct::Nested<bool = true>::Print()" << std::endl;
}
};
};
Run Code Online (Sandbox Code Playgroud)
编译器抱怨:
g++ -O0 -g3 -Wall -c -fmessage-length=0 …Run Code Online (Sandbox Code Playgroud)