std::is_reference from std::any
std::is_reference from std::any
我有点卡住了。
尝试从我的模板类内部检查参数是否是引用类型
它似乎在函数中起作用。
但是在我的函数包装器中,它总是返回 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>>
.
相关文章:
- 哪些类型可以转换为std::any
- 引用 std::any 或 not_yet_in_std::whatever 的惯用方式是什么?
- std::is_reference from std::any
- 是否可以从 std::any 创建 std::any 与 std::reference_wrapper?
- 使用 std::map 存储在 std::any 中,然后通过 std::any_cast 访问
- 可以有效地转换 std::any 与 std::any_cast
- 避免使用 std::any 编写相同的重复类型检查代码
- 广义 std::function (std::any 表示可调用对象)
- 在VS2015中访问std::any
- std::any 跨共享库边界在 mingw 中
- 将特定指针强制转换为 std::any 指针
- 检查 std::any 变量是否包含 std::string 时出现问题
- 获取 std::any 的大小
- “boost::any”和“std::any”之间的区别
- C++ std::variant vs std::any
- 是否可以将两个任意函数与 C++17 中的 std::any 进行比较
- std :: Any的商店对象类型的可能性
- 确实 boost::any / std::any 将小对象存储到位
- 将std::any转换为未知类型
- std::any by std::exception_ptr