gpt4 book ai didi

c++ - 没有定义的类声明是否有效作为模板参数

转载 作者:搜寻专家 更新时间:2023-10-31 00:54:13 25 4
gpt4 key购买 nike

使用仅声明但未定义的类的标识符作为模板参数和模板特化是否有效。

类似的东西:

template<typename T>
class NodeInfo;

template<typename T>
class GraphInfo;

template<typename T>
class Graph {
public:
GraphInfo<T> graphInfo;
NodeInfo<T> nodeInfo;
};


// specialisation
class ContextInfo;

template <>
class NodeInfo<ContextInfo> {
public:
int a, b, c;

};

template <>
class GraphInfo<ContextInfo> {
public:
int a, b, c;
};



int main() {
Graph<ContextInfo> g;
}

这在 gcc 7 中编译得很好,没有任何警告,但我想知道这是否是一件有效的事情,或者我是否用它创建了某种未定义的行为?

最佳答案

这是 fine in principle :

[ Note: A template type argument may be an incomplete type (6.9). — end note ]

但是,类类型不完整may not be used with the standard library ,除非另有说明:

[The] effects are undefined in the following cases: [...]
— if an incomplete type (6.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component.

例如:

The template parameter T of declval may be an incomplete type.

从 C++17 开始,更多的库设施允许使用不完整的类型; for example vector :

An incomplete type T may be used when instantiating vector if the allocator satisfies the allocator completeness requirements. T shall be complete before any member of the resulting specialization of vector is referenced.

关于c++ - 没有定义的类声明是否有效作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46055677/

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