可变模板函数重载 [英] Variadic template function overloading

查看:31
本文介绍了可变模板函数重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有可变模板成员函数 (foo) 的类,如下所示.这个想法是跳过参数中的所有双精度值并使用用户提供的参数分配一个对象.

I have a class with a variadic template member function (foo) like below. The idea is to skip all doubles in the parameter and allocate an object with user provided arguments.

    template <class T>
    class Var {
    public:

       template <typename U, typename ...Args>
       int foo(int index, Args... args)
       {
           T* p = new U(args...);
           // save in an array at index 'index'
       }

       template <typename U, typename ...Args>
       int foo (double index, Args... args)
       {
           // do something with index and skip it
           return foo<U>(args...);
       }
    };

    class A {
    public:
      A (int i, const char *p)
      {

      }
    };

    int main ()
    {
       Var<A> var;

       var.foo<A>(1.0, 2, 3, "Okay");
    }

现在可以了,有两个问题.

Now this works, there are 2 problem.

  • 强制跳过多少双打.例如:跳过2个双打然后下一个参数应该是一个int.如果不是,则抛出错误.

  • Enforce how many doubles to skip.Eg: skip 2 doubles and then the next argument should be an int. If it is not then throw error.

同时,使用int"代替double".所以我们将跳过 2 个整数.下一个索引将是数组的索引".

While at it, use 'int' in place of 'double'. So we will skip 2 ints. The next index will be a 'index' to an array.

基本上我想通过否.作为类模板参数跳过的整数.

Basically I want to pass the no. of ints to skip as class template parameter.

template <class T, int SKIP>
class Var {

并使用 SKIP 来确定要跳过多少个整数.

And use SKIP to determine how many ints to skip.

有没有可能做这样的事情?

Is it possible to do something like that?

推荐答案

所以这就是我从 Novelocrat 那里想到的.只是粘贴它听记录.

So this is what I conjured up taking hint from Novelocrat. Just pasting it hear for the records.

template <class T, int SKIP>
class FooHelper {
public:

    template <typename U, typename ...Args>
    static int foo_helper(int index, Args... args)
    {
        FooHelper<T, SKIP-1>::foo_helper<U>(args...);
        return 0;
    }
};

template <class T>
class FooHelper<T, 0> {
public:

    template <typename U, typename ...Args>
    static int foo_helper (Args... args)
    {
        auto p = new U(args...);
        return 0;
    }
};

template <class T, int SKIP>
class Var {
public:

    template <typename U, typename ...Args>
    int foo(Args ...args)
    {
        FooHelper<T, SKIP>::foo_helper<U>(args...);
        return 0;
    }
};

这篇关于可变模板函数重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆