1

Is there a way to write a templated class so that the signature/prototype of a member function is dependent on the template arguments? For instance, if I declare a class foo that takes an int N template argument, is it possible that the prototype of the member function foo::bar() has N same-type arguments? I am aware I cound just pass an std::array or std::vector as argument, but in the application I have in mind that wouldn't work.

template <int N>
class foo {
    std::array<float, N> _data;

 public:
    foo()  {};
    ~foo() {};

    void bar(float arg0, float arg1, float arg2 /*, ... */) const;
};
joaocandre
  • 1,621
  • 4
  • 25
  • 42

1 Answers1

2

With c++17, you can use something like std::enable_if_t as follows

#include <array>
#include <type_traits>

template <int N>
class Foo {
    std::array<float, N> _data;

public:
    explicit Foo( const std::array<float, N> & data): _data{data}{

    }
    template<typename ...Args>
    std::enable_if_t<sizeof...(Args)== N && std::is_same_v<std::common_type_t<Args...>, float>, void> bar(Args ... args) const{

    }
};

int main(){
    std::array<float, 3> data {.1, .3, .6};
    Foo<3> f {data};
    f.bar(data[0],data[1],data[2]);
    f.bar(1.0);//won't compile
    f.bar(1, 2, 3);//won't compile


}
asmmo
  • 6,922
  • 1
  • 11
  • 25
  • Thanks, it is helpful, but it doesn't really solve the problem I had in mind, which is my fault as the question is missing some details. I'll mark it as the correct answer and ask a new question with a more detailed explanation of what I am trying to achieve: https://stackoverflow.com/questions/61990155/how-to-use-class-tempalte-argument-to-change-argument-calls-and-function-signatu – joaocandre May 24 '20 at 18:02