开发者

Template spaghetti

开发者 https://www.devze.com 2023-03-11 10:11 出处:网络
Please throw some light on 开发者_运维百科that baffling piece of template spaghetti: template <typename T, typename K> class A {

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?


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消