gpt4 book ai didi

c++ - "using"创建类型别名的论据是否成立?

转载 作者:搜寻专家 更新时间:2023-10-31 02:08:51 24 4
gpt4 key购买 nike

C++11 中有一个新语法用于创建类型别名,using .可以使用,其中 typedef被使用,并且可以被模板化。 explanation这有利于using ,是这样的:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T>
typedef std::vector<T,MyAllocator<T>> Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disadvantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector<*,MyAllocator<*>> - where the asterisk is a placeholder for a type-name. Consequently, we do not propose the "typedef" syntax.

template<class T>
using Vec = std::vector<T,MyAllocator<T>>;

can be read/interpreted as: from now on, I'll be using Vect<T> as a synonym for std::vector<T,MyAllocator<T>>. With that reading, the new syntax for aliasing seems reasonably logical.

然而,我不明白。我们为类、函数使用模板,我们没有为它们单独设置关键字。那为什么我们有一个单独的关键字 typedef

即:

class Foo {
};

template <typename>
class Bar {
};

我们使用 class对于FooBar , 和 Foo是一个实际的类,但是 Bar是一个模板,类的“集合”。

有人可以阐明这一点吗?

最佳答案

除了(IMO)更大的可读性论点之外,别名模板不仅仅是别名(就像 typedef 一样,你无法以任何方式将 typedef 与其别名类型区分开来):它们真正代表了一个类型族,例如,你可以写:

template<class T>
using foo = ...;
template<template<typename> class TT> void bar();
bar<foo>();

所以 foo 不仅仅是一个别名,它是一个不同的野兽;使用过 typedef 可能会造成混淆...我认为这就是“Vec 不是类型的别名,不应被用作 typedef 名称”的意思。

关于c++ - "using"创建类型别名的论据是否成立?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47016563/

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