首页 > 解决方案 > 模板类构造函数中外部常量的奇怪问题

问题描述

我有以下三个源文件:

主.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;
}

常量.cc:

#include "constants.h"

const double pi = 3.1415;

常量.h:

#ifndef CONSTANTS_H
#define CONSTANTS_H

extern const double pi;

#endif

当我编译并链接所有内容并运行可执行文件时,我得到:

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

是什么赋予了?Foo<42> 的构造函数怎么看不到 pi 的正确值?这似乎只在 Foo 是模板时才会发生,并且只有在 pi 定义在不同的文件中时才会发生。

值得我使用 g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0。所有都--std={c++,gnu++}{98,03,11,14,17}给出相同的结果。

TIA 为您解答。

标签: c++static-order-fiasco

解决方案


推荐阅读