12.4.2的C++标准规定了这一点
[...]不得采用析构函数的地址.[...]
但是,编译器可以在没有任何抱怨的情况下获取类析构函数周围的包装器的地址,如下所示:
struct Test {
~Test(){};
void destructor(){
this->~Test();
}
};
void (Test::*d)() = &Test::destructor;
Run Code Online (Sandbox Code Playgroud)
那么禁止直接获取析构函数地址的理由是什么呢?
我正在尝试编写一个工厂类,它将具有如下所示的标准接口:
Register<MyBase, MyDerived> g_regDerived("myderived"); // register to factory
Run Code Online (Sandbox Code Playgroud)
现在打电话:
auto* d = Factory<MyBase>::instance().create("myderived", 1, 2, 3);
Run Code Online (Sandbox Code Playgroud)
将调用构造函数MyDerived(1,2,3)并返回指向创建的对象的指针
这听起来像C++ 11应该是可能的,但我无法弄清楚如何做到这一点.
从标准类型擦除工厂开始:
template<typename BaseT>
class Factory {
public:
static Factory* instance() {
static Factory inst;
return &inst;
}
template<typename T>
void reg(const string& name) {
m_stock[name].reset(new Creator<T>);
}
BaseT* create(const string& name) {
return m_stock[name]->create();
}
private:
struct ICreator {
virtual BaseT* create() = 0;
};
template<typename T>
struct Creator : public ICreator {
virtual BaseT* create() {
return new …Run Code Online (Sandbox Code Playgroud) class C {
public:
C() {}
};
template<typename T>
void func(T f) {}
int main() {
func(C);
}
Run Code Online (Sandbox Code Playgroud)
如何修复编译错误"2.cpp:9:15:错误:在'之前预期的primary-expression'"'token func(C);"?
传递类作为参数似乎很荒谬,但我想编译类似线程的函数,因为"thread(C)"工作正常:
#include <thread>
class C {
public:
C() {}
};
template<typename T>
void func(T f) {}
int main() {
std::thread(C);
}
Run Code Online (Sandbox Code Playgroud) 有没有办法从std :: map指向构造函数?我想用我想要使用的代码执行以下操作,#if 0但我似乎无法使其工作:
#include <map>
#include <functional>
using namespace std;
class Base { };
class A : public Base { };
class B : public Base { };
enum class Type { A, B, };
#if 0
using type_map_t = std::map<Type, std::function<Base*()>>;
type_map_t type_map = {
{Type::A, &A::A},
{Type::B, &B::B},
};
#endif
Base*
getBase(Type t)
{
#if 0
auto constructor = type_map[t];
return constructor();
#else
switch(t)
{
case Type::A:
return new A();
case Type::B:
return new B(); …Run Code Online (Sandbox Code Playgroud) 在C++中,是否可以在执行时加载共享库?
我希望用户选择在运行时加载哪个共享库,而无需重新编译整个程序.
dlopen() 是C的解决方案,但我的程序是用C++/Qt编写的,要提取的符号是Qt风格的类,是否有更多的"c ++"方法.
在一个项目中,我遇到了以下代码行。
::std::unordered_map<std::string, Channel*(*)(Module*, const Parameters&)>;
Run Code Online (Sandbox Code Playgroud)
有人知道 Channel*(*) 是什么意思吗?和Channel**一样吗?这对我来说似乎令人困惑和过于复杂。
Channel 构造函数如下所示:
Channel(Module* module, const util::Parameters& parameters);
Run Code Online (Sandbox Code Playgroud) c++ ×5
c++11 ×4
pointers ×2
destructor ×1
factory ×1
linux ×1
qt ×1
qt4 ×1
standards ×1
std-function ×1
stdmap ×1
templates ×1
type-erasure ×1