gpt4 book ai didi

c++ - 如何使用推导指南为 C++ 类模板提供两个兼容的名称?

转载 作者:行者123 更新时间:2023-12-04 12:30:38 24 4
gpt4 key购买 nike

如果我有一个广泛使用的名为 Foo 的类模板,我想将其重命名为 Bar 而不必自动更新其所有用户,那么直到 C+ +17 我可以简单地使用类型别名:

template <typename T>
class Bar {
public:
// Create a Bar from a T value.
explicit Bar(T value);
};

// An older name for this class, for compatibility with callers that haven't
// yet been updated.
template <typename T>
using Foo = Bar<T>;

这在处理大型分布式代码库时非常有用。然而,从 C++17 开始,这似乎被类模板参数推导指南打破了。例如,如果此行存在:

template <typename T>
explicit Foo(T) -> Foo<T>;

那么在重命名类时显而易见的事情就是将演绎指南中的 Foo 更改为 Bar:

template <typename T>
explicit Bar(T) -> Bar<T>;

但是现在随机调用者中的表达式Foo(17),本来是合法的,现在是一个错误:

test.cc:42:21: error: alias template 'Foo' requires template arguments; argument deduction only allowed for class templates
static_cast<void>(Foo(17));
^
test.cc:34:1: note: template is declared here
using Foo = Bar<T>;
^

是否有任何简单通用的方法以完全兼容的方式为具有演绎指南的类提供两个同时的名称?我能想到的最好的方法是在两个名称下两次定义类的公共(public) API,与转换运算符,但这远非简单和通用。

最佳答案

你的问题正是P1814R0: Wording for Class Template Argument Deduction for Alias Templates想要求解,也就是说,在C++20中,只需要为Bar添加推导向导,就可以让下面的程序合式:

template <typename T>
class Bar {
public:
// Create a Bar from a T value.
explicit Bar(T value);
};

// An older name for this class, for compatibility with callers that haven't
// yet been updated.
template <typename T>
using Foo = Bar<T>;

template <typename T>
explicit Bar(T) -> Bar<T>;

int main() {
Bar bar(42);
Foo foo(42); // well-formed
}

Demo.

但由于是C++20的特性,目前在C++17中还没有解决方案。

关于c++ - 如何使用推导指南为 C++ 类模板提供两个兼容的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69342182/

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