gpt4 book ai didi

时间:2019-03-17 标签:c++: how to remove cv-qualifiers of a type to access class functions?

转载 作者:行者123 更新时间:2023-12-02 03:28:48 26 4
gpt4 key购买 nike

这里是一个例子:

#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;
}

上面的代码编译并运行良好。但如果最后 3 行(调用 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>;

解释如下:

c++ copy (reference) constructor and move constructor of class cohabitation

最佳答案

问题(1)和(2)是不同的问题。

问题(1)来自以下事实:在以下std::is_invocable_v

template<typename T, 
typename ... Args>
void print(T&& t, Args&& ... args)
{
if constexpr (std::is_invocable_v<decltype(&T::display),T*,Args...>)
// no T but std::decay_t<T> ...............^...........^

您需要的是“decayed”类型,而不是T(可以作为引用)

我提议

template <typename T, typename ... Args>
void print (T && t, Args && ... args)
{
using U = std::decay_t<T>;

if constexpr ( std::is_invocable_v<decltype(&U::display), U*, Args...> )
t.display(std::forward<Args>(args)...);
else
std::cout << "not applicable !" << std::endl;
}

问题 (2) 来自以下事实:在以下 print() 调用中解释模板参数

template <typename... Args>
void run(Args&& ... args)
{
print<T,Args...>(t_,std::forward<Args>(args)...);
}

你妨碍了正确的模板推导。

建议:让模板推导,完美转发,工作原理如下

    print(t_,std::forward<Args>(args)...);

关于时间:2019-03-17 标签:c++: how to remove cv-qualifiers of a type to access class functions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60582032/

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