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

标签 c++ c++11 types

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

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/

相关文章:

c++ - std::make_pair: "cannot convert ‘int*’ 到 ‘std::pair<EndPointAddr*, EndPointAddr*>*’ 初始化”

将 float 转换为 int 指针并返回 float?

types - 关联类型默认使用特征

c++ - 如何在不溢出的情况下将Python转换为C++?

c++ - 打开失败 : No such file or directory

c++ - 私有(private) DLL 函数可公开访问

c++ - 是否存在与指针具有相同大小和对齐方式的整数类型?

c++ - 如何设置 scons 输出完整的扩展命令行?

c++ - 冲突的不匹配标签与标准库一起编译,但不以其他方式编译

c++ - 嵌套成员类型识别