0

In the following code it seems that the variadic template version of Container doesn't inherit the name function of the single template version of Container, g++ 4.5.2 complains:

no matching function for call to ”Container<Variable1, Variable2>::name(Variable2)”
candidate is: std::string Container<First_Variable, Rest ...>::name(First_Variable) [with First_Variable = Variable1, Rest = {Variable2}, std::string = std::basic_string<char>]

The code:

#include "iostream"
#include "string"

using namespace std;

struct Variable1 {
    string operator()() {
        return string("var1");
    }
};

struct Variable2 {
    string operator()() {
        return string("var2");
    }
};

template<class... T> class Container;

template<class First_Variable, class... Rest>
class Container<First_Variable, Rest...> : public Container<Rest...> {
public:
    string name(First_Variable variable) {
        return variable();
    }
};

template<class Variable> class Container<Variable> {
public:
    string name(Variable variable) {
        return variable();
    }
};

int main(void) {
    Container<Variable1, Variable2> c;
    cout << "Variables in container: " << c.name(Variable1()) << ", " << c.name(Variable2()) << endl;
    return 0;
}

What am I doing wrong or is this even supposed to work?

1 Answer 1

2

The name are hiding the name of the base class. Try

template<class... T> class Container;

template<class First_Variable, class... Rest>
class Container<First_Variable, Rest...> : public Container<Rest...> {
public:
    using Container<Rest...>::name;

    string name(First_Variable variable) {
        return variable();
    }
};

template<class Variable> class Container<Variable> {
public:
    string name(Variable variable) {
        return variable();
    }
};

If you are pedantic, then your partial specializations are incorrect. The C++11 spec terms ambiguous two partial specializations of the form <FixedParameter, Pack...> and <FixedParameter>. This was discussed and many people find it surprising, so some compilers do not implement that part of C++11.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! At least g++ up to 4.7-20120211 and clang++ 3.0 don't complain with -pedantic. Is there any other way to accomplish this or would I have to count on compilers not implementing this strictly?
@user you can specialize for <Fixed, Fixed, Pack...> and <Fixed>. But I don't think that your code will ever be rejected by compilers. So I would probably leave it as is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.