使用模板可以这样吗?
template<class T, int T::M>
int getValue (T const & obj) {
return obj.M;
}
class NotPlainOldDataType {
public:
~NotPlainOldDataType () {}
int x;
}
int main (int argc, char ** argv) {
typedef NotPlainOldDataType NPOD;
NPOD obj;
int x = getValue<NPOD, NPOD::x>(obj);
return x;
}
Run Code Online (Sandbox Code Playgroud)
我已经知道如何使用宏来做到这一点
#define GET_VALUE(obj, mem) obj.mem
class NotPlainOldDataType {
public:
~NotPlainOldDataType () {}
int x;
}
int main (int argc, char ** argv) {
NotPlainOldDataType obj;
int x = GET_VALUE(obj, x);
return x;
}
Run Code Online (Sandbox Code Playgroud) 如何立即终止我的程序(使用代码).
(我不是在寻找那些说这不是犹太人的答案.我知道不是.)
编辑:寻找Windows和Linux解决方案.
EDIT2:我试过exit,_exit,abort,并terminate没有在Windows上的成功.
编辑3:虽然我还没有访问Linux盒子,但我能够使用以下代码成功杀死我的Windows程序:
int pid = _getpid();
char buff[256];
sprintf(buff, "taskkill /pid %d /f", pid);
system(buff);
Run Code Online (Sandbox Code Playgroud) 说我有以下C++代码:
int x;
some_class y;
extern "C" {
void foo () {
// do something with x
// do something with y
}
}
Run Code Online (Sandbox Code Playgroud)
是x和/或y需要申报extern "C"?
该程序是否具有明确定义的行为?
struct Foo;
struct FooImpl {
FooImpl();
};
struct Foo : FooImpl {
int bar;
};
FooImpl::FooImpl() {
static_cast<Foo *>(this)->bar = 0;
}
int main() {
return Foo().bar;
}
Run Code Online (Sandbox Code Playgroud)
需要特别注意的是,它Foo::bar是默认初始化的。我知道如果Foo::bar被初始化Foo,这肯定是不好的,因此这个特殊的例子。
请记住,这是一个用于说明案例的简化示例。我对 C++ 规范对此的看法感兴趣(而不是这在风格上是好还是坏的代码)。