mardi 18 septembre 2018

C++11 compile fail, undefined reference, explicit class instantiation inside another class

I tried searching through stackoverflow for this example but what I find doesn't address what I'm seeing.

I'm seeing the following compile error

:(.text.startup+0x7): undefined reference to `fields::LITTLE'

For this example code snippet:

#include <iostream>
#include <string>

enum selector
{
    SELECTOR_ONE,
    SELECTOR_TWO,
};

template <selector E>
struct field_t
{
    size_t value;
    constexpr field_t(const size_t i):value(i){}
};

struct fields
{
    static constexpr field_t<selector::SELECTOR_ONE> FIRST{0};
    static constexpr field_t<selector::SELECTOR_TWO> SECOND{1};
};

int main()
{
    std::cout << fields::SECOND.value << std::endl;
    return 0;
}

I actually can make this compile by doing the following modification

#include <iostream>
#include <string>

enum selector
{
    SELECTOR_ONE,
    SELECTOR_TWO,
};

template <selector E>
struct field_t
{
    size_t value;
    constexpr field_t(const size_t i):value(i){}
};

template <selector E>
struct fields
{
    static constexpr field_t<E> FIRST{0};
    static constexpr field_t<E> SECOND{1};
};

int main()
{
    std::cout << fields<SELECTOR_TWO>::SECOND.value << std::endl;
    return 0;
}

I'm just a bit confused why the former fails to compile since that is actually what I was hoping to use default template class instantiations. Since I'm using C++11 the field_t class doesn't have external linkage (when instantiating a static constexpr field_t class) which is what putting in other fields class circumvents.

Aucun commentaire:

Enregistrer un commentaire