gpt4 book ai didi

c++ - 仅当参数可取消引用到某种类型时如何启用函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:22:12 25 4
gpt4 key购买 nike

我正在制作一个函数模板:

template <typename T>
void foo (T arg1) {}

但我想确保 T 可推导到类型 Foo,因此 arg1 需要是:

Foo * //This case T = Foo*

或者

Any type X which implements `*` operator which returns a Foo/Foo&/Foo&&

所以我需要这样的东西:

template <typename T>
void foo(T arg1, std::enable_if<std::is_same<typeid(*arg1), typeid(Foo)>::value> * = 0) {}

但这不会编译并提示:

typecheck.cpp:6:54: error: use of parameter âarg1â outside function body
void foo(T arg1, std::enable_if<std::is_same<typeid(*arg1), typeid(Foo)>::value> * = 0) {}
^

我怎样才能做到这一点?

最佳答案

你应该更喜欢 is_convertible 而不是 is_same 来捕获 Foo 的子类,模板参数列表中的 enable_if 而不是函数参数或返回类型也更容易阅读。

template <typename T, typename = typename std::enable_if<std::is_convertible<decltype( *std::declval<T>() ), Foo>::value>::type >
void foo(T arg1);

c++14 中的垃圾更少:

template <typename T, typename = std::enable_if_t<std::is_convertible<decltype( *std::declval<T>() ), Foo>::value> >
void foo(T arg1);

关于c++ - 仅当参数可取消引用到某种类型时如何启用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21389858/

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