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正规365体育投注 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;
};
| improve this question | | | | |
2

With c++17, you can use something like 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


}
| improve this answer | | | | |
  • 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: robinmaderich.com/questions/61990155/… – joaocandre 13 hours ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.