如何使用类模板参数来更改参数调用和函数签名?

问题描述 投票:0回答:1

我试图找到一种方法来设计类模板,以便传递int值,并且几个函数签名以及参数列表都依赖于此值。

特别是考虑MyClass

template <int N>
class MyClass {
    typedef SomeType<int, int, int, /* ... N times*/ > MyDepType;
    myFunction(std::string arg0, std::string  arg1, /* ...*/ std::string  argN) { /* do stuff */};
 public:
    MyClass() {
        someFunction(float arg0, float arg1, /* ...*/ float argN);   // <
        someOtherFunction(boost::bind(&MyClass::myFunction, this, _1, _2, /*...*/ _N));
    };
};

我希望能够表达私有typedef调用,myFunction的签名以及传递给外部函数someFunctionsomeOtherFunction的参数列表,但我无法对其进行编辑/重写。有没有一种方法可以使用C ++ 11标准来实现?

c++ c++11 templates variadic
1个回答
0
投票

[您可以使用本文中的技巧(Produce std::tuple of same type in compile time given its length by a template argument)来生成N个元素的元组。

template <int N, typename T> 
struct tuple_n {
    template <typename... Ts> 
    using type = typename tuple_n<N - 1, T>::template type<T, Ts...>;
};

template <typename T> 
truct tuple_n<0, T> {
    template <typename... Ts> 
    using type = std::tuple<Ts...>;
};

template <int N>
class MyClass {
    void int_function(typename tuple_n<N, int>::type&& ints);
    void float_function(typename tuple_n<N, float>::type&& floats);

    template <typename T> 
    void any_function(typename tuple_n<N, T>::type&& elements);
};
© www.soinside.com 2019 - 2024. All rights reserved.