C++ std::是std::any的_引用吗
我有点卡住了 尝试从模板类内部检查参数是否为引用类型 它似乎在函数中起作用 但在我的函数包装中,它总是返回trueC++ std::是std::any的_引用吗,c++,c++17,C++,C++17,我有点卡住了 尝试从模板类内部检查参数是否为引用类型 它似乎在函数中起作用 但在我的函数包装中,它总是返回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--) { s
#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);
}
#包括
#包括
模板
调用函数(const std::vector和args){
对于(size_t i=args.size();i>0;i--){
std::cout此处的前提不正确。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
但这实际上仍然不是一个引用,请注意,您无法使用any\u cast
-仅any\u cast
将其返回,这是因为std::any::type()的返回类型
总是const std::type_info&
,所以std::is_reference::value
总是true
。is_reference
是编译时类型特征,而type_info
包含执行期间数据类型的信息。@JorgeBellon哦,对了。你知道将参数传递给t的其他方法吗函数并循环它们?如果你想检查std::any
中的类型是否与T
匹配,你需要调用。我不想看它是否与T匹配,我需要能够拥有来自任何传递函数的任何数量的参数,然后我需要能够检查该参数是否为ref,那么你可能需要使用std::rreference\u wrapper
。我不太熟悉std::any
,但我认为它不能保存引用,就像不能声明std::vector
。然后可以通过调用std::any_cast(arg)
和std::any_cast(arg)来检查它是否是引用
并查看指针是否为空。是否确实要使用std::any
?
int i = 1;
std::any a = std::ref(i);
i = 2;
assert(std::any_cast<std::reference_wrapper<int>>(a).get() == 2);