Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::is_reference from std::any

Tags:

c++

c++17

Im a little stuck.

Trying to check if a argument is a reference type from inside my template class

It seems to work in the function.

But inside my function wrapper its always returning 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);
}
like image 951
docasok733 Avatar asked Jun 10 '26 22:06

docasok733


1 Answers

The premise here is incorrect. std::any always owns its own value. It moves/copies whatever you give it into local storage, and then is completely responsible for that independent entity:

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

The only way to store a "reference" in std::any is to store a type that itself behaves like a reference... like 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);

But that's still not actually a reference, and note that you cannot get it back out with any_cast<int> - only any_cast<reference_wrapper<int>>.

like image 145
Barry Avatar answered Jun 12 '26 13:06

Barry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!