这是一个例子:
#include <iostream>
template<typename T,
typename ... Args>
void print(T&& t, Args&& ... args)
{
// line where compilation fails when the A::run is called
if constexpr (std::is_invocable_v<decltype(&T::display),T*,Args...>)
{
t.display(std::forward<Args>(args)...);
}
else
{
std::cout << "not applicable !" << std::endl;
}
}
template<typename T>
class A
{
public:
A(T&& t):t_(t){}
template <typename... Args>
void run(Args&& ... args)
{
print<T,Args...>(t_,std::forward<Args>(args)...);
}
T t_;
};
template <typename T> A(T&) -> A<T&>;
template <typename T> A(T&&) -> A<T>;
class B
{
public:
B(int value):value_(value){}
void display(int a, int b)
{
std::cout << value_ << " "
<< a << " "
<< b << std::endl;
}
int value_;
};
int main()
{
int v1=10;
int v2=20;
B b1{1};
A a1{b1};
a1.t_.display(v1,v2);
A a2{B(2)};
a2.t_.display(v1,v2);
//a1.run(v1,v2); // (1)
//a2.run(v1,v2); // (2)
//a1.run(v1);
return 0;
}
上面的代码编译和运行都很好。但是如果取消注释最后三行(调用
run()
),就会出现以下编译错误:
(1)
main.cpp:7:48: error: ‘display’ is not a member of ‘B&’
if constexpr (std::is_invocable_v<decltype(&T::display),T*,Args...>)
(2)
注意:main.cpp:27:25: error: no matching function for call to ‘print(B&, int&, int&)’
print<T,Args...>(t_,std::forward<Args>(args)...);
template <typename T> A(T&) -> A<T&>;
template <typename T> A(T&&) -> A<T>;
在这里解释:
std::decay_t
运行良好,在线演示。 - rafix07