使用enable_if的模板函数参数推导 - 对指针的引用

Rom*_*oma 1 c++ c++11 c++03

也许有很好的解决方案适用于g ++ 4.6.{3,4}?您可以登录https://godbolt.org/

#include <type_traits>
class A{};
class B{};
class C{
    public:
    A* a;
    B* b;
};

template<typename T, typename std::enable_if<std::is_same<typename std::remove_reference<T>::type,A*>::value>::type* = nullptr >
void f(T&& t) { 
    return;
}

int main() { 
    C c;
    auto& cRef = c;
    f(cRef.a);
    f(c.a);
}
Run Code Online (Sandbox Code Playgroud)

g ++ /tmp/enable_if.cpp -std = c ++ 0x

/tmp/enable_if.cpp: In function ‘int main()’:
/tmp/enable_if.cpp:20:13: error: no matching function for call to ‘f(A*&)’
/tmp/enable_if.cpp:20:13: note: candidate is:
/tmp/enable_if.cpp:13:6: note: template<class T, typename std::enable_if<std::is_same<typename std::remove_reference<_MemPtr>::type, A*>::value, void>::type* <anonymous> > void f(T&&)
/tmp/enable_if.cpp:21:10: error: no matching function for call to ‘f(A*&)’
/tmp/enable_if.cpp:21:10: note: candidate is:
/tmp/enable_if.cpp:13:6: note: template<class T, typename std::enable_if<std::is_same<typename std::remove_reference<_MemPtr>::type, A*>::value, void>::type* <anonymous> > void f(T&&)
Run Code Online (Sandbox Code Playgroud)

小智 6

C++ 11中引入了允许您默认函数模板参数的功能.您的编译器实际上并不完全支持此功能.作为一种解决方法,您可以将std::enable_if函数作为函数返回:

template<typename T >
typename std::enable_if<std::is_same<typename std::remove_reference<T>::type,A*>::value>::type f(T&& t) { 
    return;
}
Run Code Online (Sandbox Code Playgroud)

  • @Roma - 你可以为`enable_if`指定第二个参数,它应该公开为`:: type`.所以你可以把它放在返回类型中,即使你需要返回`bool`. (4认同)