c++ - 来自 std::any 的 std::is_reference

标签 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--) {
        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 总是拥有自己的值(value)。它会将您提供给它的任何内容移动/复制到本地存储中,然后完全负责该独立实体:

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>> .

关于c++ - 来自 std::any 的 std::is_reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62215899/

相关文章:

c++ - 如何使窗口出现在所有内容之上(甚至是全屏游戏!)c++/Qt

c++ - 为什么 std::weak_ptr 没有 operator->?

c++ - 如何从 cpp 文件修改 VS_VERSION_INFO

c++ - 澄清 P0137 的细节

c++ - 如何使用可变参数模板作为 std::type_index 映射的键?

c++ - 在 constexpr 函数断点被击中

c++ - Visual Studio 2015 “non-standard syntax; use ' &' to create pointer for member”

c++ - gcc如何链接静态库?

c++ - 如果使用constexpr,是否可以删除控制流语句?

c++ - std::forward() 的右值引用重载的目的是什么?