std::is_reference from std::any

std::is_reference from std::any

本文关键字:std any from is reference      更新时间:2023-10-16

我有点卡住了。

尝试从我的模板类内部检查参数是否是引用类型

它似乎在函数中起作用。

但是在我的函数包装器中,它总是返回 true。

#include <vector>
#include <any>
template <class T>
T CallFunction(const std::vector<std::any>& args) {
for (size_t i = args.size(); i > 0; i--) {
std::cout << std::boolalpha << std::is_reference<decltype(args[i-1].type())>::value << std::endl; // always true
}
return T();
}
template<typename Fn> class FunctionBase;
template<typename R, typename... Args>
class FunctionBase <R(__cdecl*)(Args...)> {
public:
FunctionBase() {}
R operator()(Args... args) {
return CallFunction<R>({ args ... });
}
};
int foo(int a, int& b) {
std::cout << std::boolalpha << std::is_reference<decltype(a)>::value << std::endl; // falae
std::cout << std::boolalpha << std::is_reference<decltype(b)>::value << std::endl; // true
return a + b;
}
int main() {
int in = 10;
foo(1, in);
FunctionBase<decltype(&foo)> func;
func(1, in);
}

这里的前提是不正确的。std::any总是拥有自己的价值。它将您提供给它的任何内容移动/复制到本地存储中,然后对该独立实体完全负责:

int i = 1;
std::any a = i; // a owns an int whose value is 1, even though i is an lvalue here
i = 2;
assert(std::any_cast<int>(a) == 1); // still 1

std::any中存储"引用"的唯一方法是存储一个本身行为类似于引用的类型......像std::reference_wrapper

int i = 1;
std::any a = std::ref(i); 
i = 2;
assert(std::any_cast<std::reference_wrapper<int>>(a).get() == 2);

但这实际上仍然不是参考,请注意,您无法用any_cast<int>将其取回 - 只有any_cast<reference_wrapper<int>>.