简体   繁体   English

可变参数模板中对象的调用函数

[英]Call function of objects in a Variadic Template

I have a template object that can hold different data types, and a method called get() . 我有一个可以容纳不同数据类型的模板对象,还有一个名为get()的方法。 get() returns the value of the data type cast to an int . get()返回转换为int的数据类型的值。

template <class T> 
class A
{
    public:
    int get()
    {
        return (int) m_val;
    }

    void set(T t)
    {
        m_val = t;
    }

    private:
    T m_val;
};

I also have a variadic template function that would take in multiple objects of A, and call their get() methods, adding together the values and returning the result. 我还有一个可变参数的模板函数,该函数可以接受A的多个对象,并调用它们的get()方法,将值加在一起并返回结果。 However, I am fairly new to variadic templates and have no idea what I am doing. 但是,我对可变参数模板还很陌生,也不知道我在做什么。 This is what I've got, after looking around at them: 这是我环顾四周后得到的:

//Ensure only types of A can be used for getStuff
template <>
int getStuff<A>(A... t)
{
    int val = 0;
    val = val + (t...).get();
}

int main() {
    A<int> a;
    A<char> b;

    a.set(5);
    b.set(100);

    int val = getStuff(a, b);
    printf("%d", val);
    return 0;
}

Obviously, this does not compile. 显然,这不能编译。 What am I doing wrong? 我究竟做错了什么? Do I need to get a pointer to each of the different A's and iterate over them? 我是否需要获得指向每个不同A的指针并对其进行迭代?

prog.cpp:23:13: error: expected initializer before '<' token
 int getStuff<A>(A... t)
             ^
prog.cpp: In function 'int main()':
prog.cpp:37:25: error: 'getStuff' was not declared in this scope
  int val = getStuff(a, b);

You're close ! 你近了! Here is a non-recursive way, perfect-forwarding included free of charge : 这是一种非递归的方式,免费包含完善的转发功能:

template <class... As>
int getStuff(As&&... as)
{
    int val = 0;
    for(int i : {std::forward<As>(as).get()...})
        val += i;

    return val;
}

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

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