简体   繁体   English

如何在C ++中伪造可变参数函数模板?

[英]How can I fake virtual variadic function templates in C++?

The following code is impossible: 以下代码是不可能的:

struct poly_base {
    template <typename... ARGS>
    virtual void operator()(ARGS&&... args) = 0;
};

template <typename DATA>
struct poly_derived : public poly_base {
    DATA data;
    template <typename... ARGS>
    void operator()(ARGS&&... args) override {
        data(std::forward<ARGS>(args)...);
    }
};

In what ways can I fake such functionality without relying on the dynamic polymorphism provided by virtual functions? 在不依靠虚函数提供的动态多态性的情况下,可以通过哪些方式伪造此类功能? Most importantly, how can I do this without constraining the types of arguments accepted by operator() , except to those supported by the intersection of all DATA ? 最重要的是,除了所有DATA的交集所支持的参数之外,如何在不限制operator()接受的参数类型的情况下做到这一点?

If the combinations of ARGS&&... needed were known ahead of time, I'd store the necessary function pointers in poly_base , or declare the necessary pure virtual functions. 如果提前知道所需的ARGS&&...的组合,则可以将必要的函数指针存储在poly_base ,或者声明必要的纯虚函数。 But how can I do this without constraining the argument types? 但是,如何在不限制参数类型的情况下做到这一点呢?

Were such a thing possible, I'd expect the compiler to generate a vtable with the union of all poly_base::operator() overloads invoked in all translation units for each DATA with which poly_derived is instantiated. 如果有这种可能,我希望编译器针对实例化了poly_derived每个DATA ,在所有转换单元中调用的所有poly_base::operator()重载的联合生成一个vtable。 How can I fake such a thing myself using variadic templates, function pointers, and template variables? 我如何使用可变参数模板,函数指针和模板变量来伪造此类东西?

Clarification: I don't want to type-erase ARGS . 澄清:我不想键入ARGS They should be known to the caller and to the callee. 呼叫者和被呼叫者都应该知道它们。 I only want to erase DATA . 我只想删除DATA

The answer is simple. 答案很简单。 You don't. 你不知道

The set of arguments that a single type supports in C++ is Halt-complete; C ++中单个类型支持的参数集是Halt-complete; you couldn't even do this for a single DATA type where you type erase all valid arguments in a known table. 您甚至无法对单个 DATA类型执行此操作,在该类型中,键入会擦除已知表中的所有有效参数。

On top of that, the set of types derived from a class is not available anywhere with dynamic linking, it is not even known at link time. 最重要的是,从类派生的类型集在动态链接的任何地方都不可用,甚至在链接时也不知道。

使用C可变参数可以解决ABI问题,但是我不知道它是否可以与关键字virtual一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM