0

I have the following code:

    struct All { 
    All() {} 
    ~All() {}

    template <typename T>
    static struct Item {
        T var;
    } item;
    virtual void setVal() noexcept {} 
};

template <typename T>
struct any : public All
{
    public:
        any() : All() {}
        ~any() {}
        T value; 
        void setVal() noexcept override {
            All::item<decltype(value)>.var = value; // Error appears here
        }
};

And the following error:

undefined reference to All:item<int>

I don't understand this error, because item is a static member variable template, and i have to specialize it...

Help me !

  • 2
    And the C-tag was just for decoration? Why not add D, Rust and Java tags, too? – too honest for this site Aug 27 '15 at 01:04
  • @Olaf No, template, struct, static..., are also available in C. – rangerprice Aug 27 '15 at 01:11
  • By which standard? Pointers please! – too honest for this site Aug 27 '15 at 01:12
  • @rangerprice `template` is definitely not a C thing. On the other topic, your code does seem strange. What are you trying to achieve? [boost.variant](http://www.boost.org/doc/libs/1_58_0/doc/html/variant.html)? – Rostislav Aug 27 '15 at 01:15
  • @Rostislav: The whole syntax is not C. With the same argument as OP one could add Python and Ruby as they use the same syntax for integer literals, colons and various keywords (`if`, ...). – too honest for this site Aug 27 '15 at 01:16
  • @Rostislav I want to do an equivalent of boost.any, but it's very difficult for me. – rangerprice Aug 27 '15 at 01:21
  • @Olaf indeed, you are absolutely right - constructors, destructors, member functions, inheritance, etc... @rangerprice Well, then your static struct will not do any good anyway. Imagine you have two of `any` that hold an int. They would then share the same value if what you wrote was valid C++. What you need is type erasure - a good in-depth description could be found on Andrzej's blog starting [here](https://akrzemi1.wordpress.com/2013/11/18/type-erasure-part-i/). – Rostislav Aug 27 '15 at 01:32

1 Answers1

0

Your bug is that you never defined the static member variable. You only declared it. Add a definition:

template <typename T>
All::Item<T> All::item = {};

However, your syntax for defining the type of the member variable template and declaring the variable itself is not accepted by the compilers that I tested. g++ (5.2.0) is fine with the declaration, but complains that All::Item is not a template when specifying the type for the variable definition. clang++ (3.6.0) does not even accept your declaration. Simply separating the definition of the type and the declaration of the variable solved the issue:

template <typename T>
struct Item {
    T var;
};

template <typename T>
static Item<T> item;
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • If you can grok standardese, then you may want to check whether your syntax is even allowed or not. – eerorika Aug 27 '15 at 01:58