c++ - void function(...) 和 void 类型的 std::is_same?

标签 c++ typetraits std-function

我得到了这段代码:

template <class FunctionType> class Entry {
    std::function<FunctionType> internalFunction;

    template<class... Arguments>
    auto operator()(Arguments... arguments) -> decltype(internalFunction(arguments...)){

        if (std::is_same<decltype(internalFunction(arguments...)), void>::value) {
            internalFunction(arguments...);
        } else {
            auto result = internalFunction(arguments...);

            return result;      
        }
    }
};

入口类是std::function 的包装器。它适用于所有返回类型,只有一个异常(exception) - void。我无法让它工作。我也尝试过 std::is_void,它不会为 void(...) 类型的函数返回 true。 std::is_same 也是如此。

如何解决这个问题?

最佳答案

return internalFunction(arguments...);

即使 internalFunction 返回 void 也能正常工作

尝试将结果存储在中间对象中是行不通的,因为您不能创建 void 类型的对象,因为它不是对象类型。

你的 if 不起作用,因为 if 是一个运行时条件,编译器仍然需要编译条件的两个分支,所以它们都必须有效C++。

如果您需要创建一个中间结果类型的变量,那么您不能将该代码用于 void 情况。您可以为返回 void 的函数编写部分特化:

template <class FunctionType> class Entry {
    std::function<FunctionType> internalFunction;

    template<class... Arguments>
    auto operator()(Arguments... arguments) -> decltype(internalFunction(arguments...))
    {

        auto result = internalFunction(arguments...);

        return result;      
    }
};

template <class... ArgTypes> class Entry<void(ArgTypes...)> {
    std::function<void(ArgTypes...)> internalFunction;

    template<class... Arguments>
    void operator()(Arguments... arguments) {
        internalFunction(arguments...);
    }
}; 

这对返回 void 的函数不起作用,但对返回 void 的仿函数不起作用,这样做有点困难。

关于c++ - void function(...) 和 void 类型的 std::is_same?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35710392/

相关文章:

c++ - 将 std::sort 限制为随机访问迭代器

c++ - 如何确定一个参数是否是一个纯函数指针?

C++ 如何使用 std::bind/std::function 引用模板函数

c++ - 使用 throw() 说明符模拟方法

c# - 获取由 3d 多边形包围的点

c++ - 单例实例作为静态字段与 getInstance() 方法中的静态变量

c++ - CMake使add_library依赖于ExternalProject_Add

c++ - 测试类型是否为分配器的正确方法是什么?

c++ - 如何通过绑定(bind)另一个成员函数的参数来创建 C++ 成员函数?

c++ - 尽管明确声明了返回类型,但对 lambda 的调用仍不明确