Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template spaghetti

Please throw some light on that baffling piece of template spaghetti:

template <typename T, typename K> class A {
public:
    T t;
    K k;

    template <int i, int unused = 0> struct AttributeType {
    };

    template <int i> AttributeType<i> getAttr();

};

template <typename T, typename K> template <int i> A<T, K>::AttributeType<i> A<T, K>::getAttr<i>() {
    return t;
}

I'm not able to come up with the correct syntax to define the implementation of A::getAttr(). The current code fails to compile at the line of getAttr definition:

error: function template partial specialization ‘getAttr<i>’ is not allowed

How should I rephrase the function definition?

like image 655
ognian Avatar asked Jun 03 '11 20:06

ognian


1 Answers

Remove that <i> behind the function name and add a typename right before the return type, it's a dependent name. Also, it's missing a template before AttributeType because that's a template:

template <typename T, typename K>
template <int i>
typename A<T, K>::template AttributeType<i> A<T, K>::getAttr() {
    return t;
}

Next, it is helpful to give each template part its own line. Makes stuff clearer.

Aside from that, the function looks wrong, or does AttributeType have a conversion constructor from T?

like image 162
Xeo Avatar answered Oct 16 '22 20:10

Xeo