考虑以下类别:
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/