调用较少约束的功能等效函数 [英] Call less constrained functionally equivalent function

查看:51
本文介绍了调用较少约束的功能等效函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

#include <iostream>
#include <type_traits>

struct A;

template<class T>
concept HasParent = std::is_convertible_v<typename T::parent*, A*>;

struct A{};

struct B : A { using parent = A; };

template<class T>       int foo(T*) { return 1; }

template<HasParent T>   int foo(T*)
{
  // call the other one?
  return 2;
}

int main()
{
  B b;
  std::cout << foo(&b) << std::endl; // displays 2
  return 0;
}

是否可以从 foo< HasParent T>(T *)调用通用的 foo< T>(T *)函数?

Is it possible to call the general foo<T>(T*) function from foo<HasParent T>(T*)?

(这是一个(功能性的)示例,但是我可以在github上链接完整的代码)

推荐答案

是否可以从 foo< HasParent T>(T *)调用通用的 foo< T>(T *)函数?

您需要 some 方式来区分这两个功能.

You need some way to differentiate between the two functions in order to do this.

例如:

template <typename T>               void foo(T);
template <typename T> requires true auto foo(T) -> int;

对于所有 T ,第二个显然比第一个更受约束,因此 foo(42)称为第二个.但是,您可以 区分两者:

The second one is obviously more constrained than the first, for all T, so foo(42) calls the second. But, you can differentiate between the two:

auto unconstrained = static_cast<void(*)(int)>(foo);

在这里,受约束的函数模板返回 int ,因此它不是可行的候选者,而我们得到了不受约束的模板.

Here, the constrained function template returns int so it's not a viable candidate and we get the unconstrained one instead.

在您的示例中,两个都返回 int ,因此此特殊技巧不起作用.但是关键是您需要 some 方法来区分这两个模板.

In your example, both return int, so this particular trick doesn't work. But the key is that you need some way to differentiate the two templates.

更好的方法可能是:

template <typename T, std::monostate M = {}>
void foo(T);

template <typename T> requires true
void foo(T arg) {
    foo<T, std::monostate{}>(arg); // calls the unconstrained one
}

在这里使用 monostate 有点可爱,因为它实际上并没有改变模板实例化的数量(只有一个 monostate ...). foo(42)调用第二个,后者调用第一个.演示.

Using monostate here is kinda cute since it doesn't actually change the number of template instantiations (there's only one monostate... ). foo(42) calls the second, which calls the first. Demo.

但是最好只是添加一个新函数,并让函数模板的不受约束版本和受约束版本都调用该函数(从某种意义上说,它比 monostate 方法具有更少的神秘性)

But it might be better to just add a new function and have both the unconstrained and constrained version of the function template invoke that one (in the sense that it's arguably less cryptic than the monostate approach).

这篇关于调用较少约束的功能等效函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆