gpt4 book ai didi

c++ - 为什么 const 变量不需要在模板类中初始化,直到实际使用该类?

转载 作者:行者123 更新时间:2023-12-02 18:46:02 25 4
gpt4 key购买 nike

如果我不在未使用的模板类中初始化 const 变量,为什么编译器不会抛出错误?如果我删除 template 关键字,编译器会按预期发出提示。

此代码有效(意外):

#include <iostream>

template<class T>
class Matrix {
private:
const uint8_t numRows, numColumns;
T content[];

public:
Matrix(uint8_t numRows, uint8_t numColumns)
// : numRows(numRows), numColumns(numColumns) -- Works fine
{
std::cout << "Matrix" << std::endl;
}
};

int main() {
// If Matrix constructor is not called the compiler doesn't need a initialization list
// Matrix<int> matrix(2, 2);
return 0;
}

但是这个没有(预期):

#include <iostream>

template<class T>
class Matrix {
private:
const uint8_t numRows, numColumns;
T content[];

public:
Matrix(uint8_t numRows, uint8_t numColumns)
// : numRows(numRows), numColumns(numColumns) -- Does NOT work
{
std::cout << "Matrix" << std::endl;
}
};

int main() {
Matrix<int> matrix(2, 2);
return 0;
}

最佳答案

Class template在需要之前不会隐式实例化。您不使用Matrix<int> ,那么它就不会被实例化,并且不需要定义(存在或格式良好)。

When code refers to a template in context that requires a completely defined type, or when the completeness of the type affects the code, and this particular type has not been explicitly instantiated, implicit instantiation occurs. For example, when an object of this type is constructed, but not when a pointer to this type is constructed.

根据标准,[temp.inst]/2 :

Unless a class template specialization is a declared specialization, the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program.

[temp.inst]/11 :

(强调我的)

An implementation shall not implicitly instantiate a function template, a variable template, a member template, a non-virtual member function, a member class or static data member of a templated class, or a substatement of a constexpr if statement ([stmt.if]), unless such instantiation is required.

因此,在这种情况下,格式不正确的 Matrix<T>::Matrix(uint8_t numRows, uint8_t numColumns)不允许隐式实例化。

关于c++ - 为什么 const 变量不需要在模板类中初始化,直到实际使用该类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67430095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com