Search code examples
c++templatesinheritancevariadic-templatesvariadic-functions

Variadic template qualifiers


I have a templated interface with a variable number of parameters:

template <typename... Args>
class Base {
public:
    virtual void f(Args...) = 0;
};

Then I inherit another class from it:

class Derived : public Base<std::string, int, float> {
public:
    void f(std::string, int, float) override {}
};

Here I would like to pass a string(or other large object) by a constant reference. I understand that I can do this:

template <typename... Args>
class Base {
public:
    virtual void f(const Args&...) = 0;
};

class Derived : public Base<std::string, int, float> {
public:
    void f(const std::string&, const int&, const float&) override {}
};

But then the primitive types must also be passed by reference.
Can I achieve something similar?

class Derived : public Base<std::string, int, float> {
public:
    void f(const std::string&, int, float) override {}
};

Solution

  • Something like this? Adjust the condition as needed.

    template <typename... Args>
    class Base {
    public:
        virtual void f(std::conditional_t<std::is_scalar_v<Args>, Args, const Args&>...) = 0;
    };
    

    Though I agree with @asynts. If it was my code, I'd pass by const reference unconditionally.