c++ - 模板类构造函数中外部常量的奇怪问题
问题描述
我有以下三个源文件:
主.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 为您解答。
解决方案
推荐阅读
- r - 仅使用系数矩阵预测 glm 回归,没有 glm 对象
- javascript - 如何在 Jquery 中为动态下拉列表创建循环?
- node.js - 如何向传入的响应数据添加属性?
- ios - 如何在iOS应用上的同一wifi网络中录制屏幕并广播到智能电视?
- c++ - 关于“::operator new”的问题
- sql - 如何使用两个单独的带有 SQL 的数组访问特定值(一个带有名称,另一个带有值)
- spark-streaming - 火花流不读取新的本地文件
- java - 在现代应用程序设计中,如何在 TransferOject 和 BusinessObject 之间实现 /
- python - Yolo v5 将所有 nginx 核心用于单个请求
- php - 为什么我在 PHP 中收到“通知:未定义的索引”错误