A1987dM
A1987dM

Reputation: 11

Weird issue with external constants in constructor of template classes

I have the following three source files:

main.cc:

#include "constants.h"
#include <cstdlib>
#include <iostream>

template <std::size_t n> class Foo {
    public:
    static const double bar;
    Foo();
};

template <std::size_t n> const double Foo<n>::bar = 4*pi;

template <std::size_t n> Foo<n>::Foo() { std::cout << "ctor: " << bar << std::endl; }

const Foo<42> baz;

int main(void)
{
    std::cout << "main(): " << Foo<42>::bar << std::endl;
    std::cout << "main(): " << baz.bar << std::endl;
    return 0;
}

constants.cc:

#include "constants.h"

const double pi = 3.1415;

constants.h:

#ifndef CONSTANTS_H
#define CONSTANTS_H

extern const double pi;

#endif

and when I compile and link everything and run the executable I get:

ctor: 0
main(): 12.566
main(): 12.566

What gives? How comes the constructor of Foo<42> can't see the correct value of pi? This seems to only happen if Foo is a template, and only if pi is defined in a different file.

For what it's worth I'm using g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0. All of --std={c++,gnu++}{98,03,11,14,17} give the same results.

TIA for your answers.

Upvotes: 1

Views: 67

Answers (0)

Related Questions