是否可以使用 c++20 的概念来模拟多态性?
Is it possible to mimic polymorphism using concepts with c++20?
标题中的问题差不多。 Please considere the following godbolted code:
#include <iostream>
struct Base{};
struct Derived : Base{};
template<typename T>
concept IsDerivedFromBase = std::same_as<T, Base>;
template<typename T>
concept IsNotDerivedFromBase = not IsDerivedFromBase<T>;
template <IsDerivedFromBase T>
void foo(T bar) {std::cout << "IsBase" << std::endl;}
template <IsNotDerivedFromBase T>
void foo(T bar) {std::cout << "IsNotBase" << std::endl;}
int main()
{
Base a;
foo(a);
Derived b;
foo(b);
Base* c = new Derived{};
foo(*c);
delete c;
}
以上代码的输出为:
IsBase
IsNotBase
IsBase
我想问是否可以通过某种方式修改这些概念以模仿多态性。
输出应为:
IsBase
IsNotBase
IsNotBase
所有与概念相关的东西都是在编译时确定和“解决”的。暂时搁置SFINAE:失败的概念要求导致程序格式错误和编译失败。
另一方面,C++ 中唯一可能“知道”您的 c
没有“真正”指向 Base
的部分是 dynamic_cast
,它会被求值在 运行时。就 C++ 中的其他所有内容而言,您的 c
指向一个 Base
实例,讨论到此结束。
因此,总而言之,就此处在编译时评估的所有内容而言,您的 c
指向 Base
并且没有其他概念可以使用,这将指示其他内容。
标题中的问题差不多。 Please considere the following godbolted code:
#include <iostream>
struct Base{};
struct Derived : Base{};
template<typename T>
concept IsDerivedFromBase = std::same_as<T, Base>;
template<typename T>
concept IsNotDerivedFromBase = not IsDerivedFromBase<T>;
template <IsDerivedFromBase T>
void foo(T bar) {std::cout << "IsBase" << std::endl;}
template <IsNotDerivedFromBase T>
void foo(T bar) {std::cout << "IsNotBase" << std::endl;}
int main()
{
Base a;
foo(a);
Derived b;
foo(b);
Base* c = new Derived{};
foo(*c);
delete c;
}
以上代码的输出为:
IsBase
IsNotBase
IsBase
我想问是否可以通过某种方式修改这些概念以模仿多态性。 输出应为:
IsBase
IsNotBase
IsNotBase
所有与概念相关的东西都是在编译时确定和“解决”的。暂时搁置SFINAE:失败的概念要求导致程序格式错误和编译失败。
另一方面,C++ 中唯一可能“知道”您的 c
没有“真正”指向 Base
的部分是 dynamic_cast
,它会被求值在 运行时。就 C++ 中的其他所有内容而言,您的 c
指向一个 Base
实例,讨论到此结束。
因此,总而言之,就此处在编译时评估的所有内容而言,您的 c
指向 Base
并且没有其他概念可以使用,这将指示其他内容。