是否可以为包中的每个参数声明一个方法

Is it possible to declare a method for each parameter in a pack?

本文关键字:声明 方法 一个 参数 是否 包中      更新时间:2023-10-16

例如:

template<class... keys>
struct{
    { virtual keys* getContents(foo* Foo) const = 0 }...;
}

或:

template<class... keys>
struct{
    virtual bar* getBar( keys* Foo )... const = 0;
}

或者有类似效果的东西?

函数或方法不能返回参数包。

函数可以返回std::tuple,不过:

template<class... keys>
struct something {
    virtual std::tuple<keys...> getContents(foo* Foo) const = 0;
}

您也可以将此模板专门化为单个类型,并返回该类型,而不是一个单元素元组;并将其专门化为空参数包,并返回void

编辑:

你澄清了你的问题。你试图做一些不同的事情,你最初的解释有点离谱,这是可以理解的。

你可以完成你想要的,但它有点复杂,需要递归模板和专业化,但看起来这就是你想要的。

class bar;
template<typename ...Keys> struct getcontents_base;
template<>
struct getcontents_base<> {
};
template<typename firstKey, typename ...remainingKeys>
struct getcontents_base<firstKey, remainingKeys...>
    : getcontents_base<remainingKeys...> {
    virtual bar *getBar(firstKey *foo) const=0;
};
struct getcontents : public getcontents_base<int, char> {
    bar *getBar(int *) const override {}
    bar *getBar(char *) const override {}
};
struct notgetcontents : public getcontents_base<int, char> {};
void foo()
{
    struct getcontents c; // This will compile fine.
    struct notgetcontents c2; // This will result in a compilation error
                              // because the virtual methods have not
                              // been defined.
}