如何避免这段代码中的void赋值

How can I avoid the void assignment in this code?

本文关键字:void 赋值 代码 何避免 段代码      更新时间:2023-10-16

我有一个可以为空的VariantType,即具有空状态。

使用Mingw Builds x64 5.3.0编译时,下面的代码会产生错误:

error: conversion from 'void' to non-scalar type 'VariantType {aka utils::Variant<bool, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >}' requested|

如何避免错误:

#include <Common/Variant.hpp>
using namespace utils;
#include <vector>
#include <unordered_map>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <map>
using VariantType = Variant<bool,int,std::string>;
class EFBase
{
public:
    virtual ~EFBase() {}
};
template<typename FuncSig>
class EF : public EFBase
{
public:
    EF(std::function<FuncSig> func) : m_function(func) {};
    std::function<FuncSig> m_function;
};
class Functions
{
public:
    using FuncMap = std::map<std::string,EFBase*>;
    FuncMap m_functions;
    template<typename FuncType>
    void Add(const std::string name, FuncType function)
    {
        m_functions.emplace(FuncMap::value_type(name,new EF<FuncType>(std::function<FuncType>(function))));
    }
    template<typename... Args>
    VariantType Invoke(const std::string& name, Args... args)
    {
        auto itr = m_functions.find(name);
        if(itr == m_functions.end())
            return VariantType();
        typedef void Func(typename std::remove_reference<Args>::type...);
        std::type_index index(typeid(Func));
        const EFBase& a = *itr->second;
        std::function<Func> func = static_cast<const EF<Func>&>(a).m_function;
        if(typeid(typename std::function<Func>::result_type) == typeid(void))
        {
            func(std::forward<Args>(args)...);
            return VariantType();
        }
        else
        {
            VariantType x = func(std::forward<Args>(args)...);
            return x;
        }
    }
};
int main()
{
    Functions f;
    f.Add<int(bool)>("get3",[](bool x) { return 3; });
    VariantType v = f.Invoke<>("get3",true);
    return 0;
}

我本以为检查函数对象的result_type就足够了;但我猜不是因为模板实例化。我是否需要一种辅助结构,在void情况下(基于模板参数)做一些不同的事情?

代码的目的是将任意签名的函数按名称存储在map中,以便以后调用。VariantType处理多个可能的返回值。

错误是在Invoke方法的else块中的赋值。

VariantType是一段相当长的代码,所以我没有提供它(我不确定它是否相关)。但是如果需要的话我可以。

根据确切的用例,一个建议是将std::function<VariantType(x)> s存储在映射中(x是一些固定的参数集),其思想是使用函子包装器进行存储,使函数适应特定的签名。传递给Add的客户端函数要么(a)需要封装在具有正确签名的函子中,要么(b)如果您知道传递给Add的所有不同类型的函数,则可以定义template<typename F, typename ...Args> Add(F f),并基于std::result_of<F(...Args)>对其进行专门化,以便Add可以制作包装器。您也可以采用混合方法,要求客户端传递符合固定参数列表的函数,并且Add可以根据传入函数的返回类型包装这些函数以返回VariantType s。

下面的例子展示了一些概念。

注意,SFINAE原则被应用于wrapper模板重载,以避免编译器在我们不希望它计算的专门化中失败(f返回void的那个)。

还要注意,我认为在运行时需要根据函数类型调度不同的参数列表的情况可能会困难得多,因此这里的方法试图通过在创建回调时捕获参数列表来规范化参数列表。如果你真的认为你需要Invoke中的可变参数列表,那么我建议也许可以考虑使用boost::any来包装函数,或者至少作为概念指导。

#include <iostream>
#include <type_traits>
#include <functional>
#include <string>
#include <map>
#include <vector>
template<typename T1, typename T2, typename T3>
struct Variant
{
    Variant() { std::cout << "In void Ctor of Variant" << std::endl; }
    template<typename T> Variant(T t) { std::cout << "In data Ctor of Variant" << std::endl; }
};
using VariantType = Variant<bool,int,std::string>;
using FuncSig = std::function<VariantType(int)>;

struct Functions
{
    template<typename F, typename Result = typename std::result_of<F(int)>::type >
    void Add(const std::string name, F f)
    {
        this->m_functions.emplace(name, [=](int i) { return wrapper<F, Result>(f, i); });
    }
    VariantType Invoke(const std::string& name, int i)
    {
        auto itr = m_functions.find(name);
        if(itr == m_functions.end())
            return VariantType();
        return itr->second(i);
    }
private:
    using FuncMap = std::map<std::string,FuncSig>;
    FuncMap m_functions;
    template<typename F, typename ReturnValue, typename ...Args>
    static typename std::enable_if<!std::is_same<ReturnValue, void>::value, VariantType>::type wrapper(F f, Args&&... args)
    {
        VariantType x = f(std::forward<Args>(args)...);
        return x;
    }
    template<typename F, typename ReturnValue, typename ...Args>
    static typename std::enable_if<std::is_same<ReturnValue, void>::value, VariantType>::type wrapper(F f, Args&&... args)
    {
        f(std::forward<Args>(args)...);
        return VariantType();
    }
};
struct Client
{
    Client(Functions& funcs)
    {
        funcs.Add("v_func", [&](int i) { this->v_func(this->d, i); } );
        funcs.Add("b_func", [&](int i) { return this->b_func(i); } );
        funcs.Add("s_func", [&](int i) { return this->s_func(i, this->some_string); } );
        funcs.Add("i_func", [&](int i) { return this->i_func(i); } );
    }
    void v_func(double d, int i) const { std::cout << this->obj_name << ": v_func()" << d << ", " << i << std::endl; }
    bool b_func(int i) const { std::cout << this->obj_name << ": b_func()" << i << std::endl; return i > 5; }
    std::string s_func(int i, std::string const& s) const { std::cout << this->obj_name << ": s_func()" << i << ", " << s << std::endl; return s; }
    int i_func(int i) const { std::cout << this->obj_name << ": i_func()" << i << std::endl; return i + 10; }
    std::string obj_name;
    const std::string some_string = "some_string";
    const double d = 3.14;
};
int main()
{
    VariantType variant;
    Functions functions;
    Client c(functions);
    c.obj_name = "Client1";
    std::vector<std::string> v = { "s_func", "b_func", "v_func", "i_func" };
    int i = 0;
    for (auto s : v) { variant = functions.Invoke(s, i++); }
    return 0;
}

输出:

In void Ctor of Variant
Client1: s_func()0, some_string
In data Ctor of Variant
Client1: b_func()1
In data Ctor of Variant
Client1: v_func()3.14, 2
In void Ctor of Variant
Client1: i_func()3
In data Ctor of Variant

(在本文中,"生成代码"意味着执行类型替换、选择专门化等)

是的;当你想根据模板参数的属性生成不同的代码时,你需要使用专门化。

将代码隐藏在未执行的块中会阻止执行,但不会阻止代码生成。

不一定是helper结构体;你可以使用标签:

VariantType InvokeHelper(/* args here */, std::true_type) ;
VariantType InvokeHelper(/* args here */, std::false_type) ;
// ...
return InvokeHelper(/* */, std::is_same</* function result*/, void>);

,但帮助结构可能是更好的选择。