【发布时间】:2016-03-08 09:24:23
【问题描述】:
我想在typename U 到typename T 之间添加相同的数字指针,例如当T = int*** 和U = int* 时,结果是int****。所以,我写了以下内容:
#include <type_traits>
template <typename T, typename U,
typename std::enable_if_t<std::is_pointer<U>::value>* = nullptr>
auto addPointer(T, U)
-> decltype(addPointer(std::declval<std::add_pointer_t<T>>(),
std::declval<std::remove_pointer_t<U>>()));
template <typename T, typename U,
typename std::enable_if_t<!std::is_pointer<U>::value>* = nullptr>
auto addPointer(T, U) -> T;
int main()
{
using t =
decltype(addPointer(std::declval<int***>(), std::declval<int*>()));
}
我在 Linux clang 3.7 上得到以下信息:
$ clang++ -std=c++14 -stdlib=libc++ -lc++abi -Wall -Wextra a.cpp
a.cpp:16:18: error: no matching function for call to 'addPointer'
decltype(addPointer(std::declval<int***>(), std::declval<int*>()));
^~~~~~~~~~
a.cpp:5:6: note: candidate template ignored: substitution failure [with T = int ***, U =
int *, $2 = nullptr]: call to function 'addPointer' that is neither visible in the
template definition nor found by argument-dependent lookup
auto addPointer(T, U)
^
/usr/bin/../include/c++/v1/type_traits:244:78: note: candidate template ignored: disabled
by 'enable_if' [with T = int ***, U = int *]
...<bool _Bp, class _Tp = void> using enable_if_t = typename enable_if<_Bp, _Tp>::type;
^
1 error generated.
为什么我会收到错误消息?
【问题讨论】:
-
将
auto addPointer(T, U) -> T;版本移到另一个重载之前 -
使用这么多级别的间接是code smell。
-
@PiotrSkotnicki
U = int*有效,但U = int**导致同样的错误... -
只是出于好奇:您曾经可以用它做什么? :-)
-
@matz 我的 TMP 练习库 :)
标签: c++ metaprogramming c++14 template-meta-programming sfinae