c++ - 在模板推导中使用boost变量

标签 c++ class templates vector template-argument-deduction

考虑以下类别:

template <typename classTypeT>
class myClass {
public:    
    using FunctionType1 = std::function<void(classTypeT &, const std::string*)>;
    using FunctionType2 = std::function<void(classTypeT &, const int)>;
    using FunctionVariantType = boost::variant<FunctionType1, FunctionType2>;

    std::vector<FunctionVariantType> myVariants;

    myClass(const std::vector<FunctionVariantType> myVec) {
        myVariants = myVec;
    }
};

并创建该类的实例:
auto vec = std::vector<myClass<SomeOtherClass>::FunctionVariantType>({&SomeOtherClass::someFunc});
auto classInstance = myClass<SomeOtherClass>(vec);

这段代码可以工作并且可以实现我想要的功能,但是我真的想避免必须在vector中指定模板类型。即,我希望能够做到这一点:
auto vec = std::vector({&SomeOtherClass::someFunc});
auto classInstance = myClass<SomeOtherClass>(vec); // Error

并进行一些模板删除,但是出现了这样的错误:
cannot convert argument 1 from 'std::vector<void (__cdecl myClass::* )(const std::string *),std::allocator<_Ty>>' to 'const std::vector<mwboost::variant<std::function<void (classTypeT &,const std::string *)>,std::function<void (classTypeT &, const int)>>,std::allocator<_Ty>> &'

看起来无法将函数类型隐式转换为该函数类型的变体吗?如果没有 vector ,这似乎更好地工作,但是我不应该仍然可以这样做吗?

谢谢,

瑞安

最佳答案

您可以使用initializer_list FunctionVariantType :

template <typename T>
class myClass {
public:
    using FunctionType1 = std::function<void(T&, const std::string*)>;
    using FunctionType2 = std::function<void(T&, const int)>;
    using FunctionVariantType = std::variant<FunctionType1, FunctionType2>;

    std::vector<FunctionVariantType> myVariants;

    myClass(std::initializer_list<FunctionVariantType> myVec)
        : myVariants(myVec) {}
};

int main()
{
    auto func1 = [](int&, const std::string*) {};
    auto func2 = [](int&, const int) {};

    myClass<int> myInst({func1, func2});
}

之所以可行,是因为vector也有一个采用initializer_list的构造函数。

关于c++ - 在模板推导中使用boost变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61528504/

相关文章:

c++ - 无法将带有 bool 网格的文本文件读入 vector 的 vector 中

c++ - 在类成员中调用函数 (C++)

css - 设置临时/相对根 CSS 选择器?

C++ 模板完整指南。赋值运算符

c++ - gcc 4.5.1 vs VC2010 模板部分特化 : which is C++0x conformant?

c++ - 我如何限制堆的大小,这样当我分配很多时它不会让机器卡住?

c++ - C/C++ 指针技巧修复

php - 如何在 PHP 中处理包含所需的类

c++ - 非类型模板数组?

java - 将 C++ long 类型转换为 JNI jlong