我手头有一个模板繁重的代码,其中应该用作用户代码的模板参数的类具有不同的构造函数签名。我的问题是,我还没有找到在我的用户代码中调用模板类的构造函数的好方法。一个最小的工作示例可能如下所示:
#include <string>
#include <iostream>
#include <memory>
class ShortConstructorInLibrary {
std::string myName;
static const int tag = 1;
public:
ShortConstructorInLibrary(std::string name) :
myName(name) {
}
};
class LongConstructorInLibrary {
private:
int a;
double b;
public:
static const int tag = 2;
LongConstructorInLibrary(int arg1, double arg2) :
a(arg1), b(arg2) {
}
};
//above is library code
template<typename T>
class MyClass {
std::shared_ptr<T> member_p;
//i want to call right constructor for both cases:
public:
MyClass() {
//how do i call the different constructors properly?!
member_p = std::shared_ptr<T>(new T("test"));
}
};
int main() {
MyClass<ShortConstructorInLibrary> obj; //works
//MyClass<LongConstructorInLibrary> obj2; // wrong constructor signature
}
这里我在一个库中有两个类,一个有一个长且不相关的构造函数签名,一个有一个短的。我希望能够将它们都用作模板参数。在我的 userClass 中,我必须以某种方式定义要根据传递的类型传递给构造函数的参数。
我不能使用简单的 if() 因为编译器会检查两个签名,一个会出错。我不能将 c++17 用于“if constexpr(){}”。
我可以将模板参数“ShortConstructorInLibrary”传递给我的类并完美地调用它的构造函数,但是当我使用另一个类时,它当然会因构造函数签名错误而失败。到目前为止,我使用了一个丑陋的技巧,我实现了两个辅助方法,我在其中传递一个指针,然后让这两个方法实现构造函数调用,但这对我来说似乎很丑陋。我还摆弄了 std::enable_if<> ,但并没有走得太远。@Mohit 建议使用部分模板特化,但在现实世界的代码中,Short ConstructorInLibrary 类本身是用几个 ...templated 模板参数进行模板化的。给你一个想法:
‘class CFEM_LOP<Dune::PDELab::QkLocalFiniteElementMap<Dune::GridView<Dune::DefaultLeafGridViewTraits<const Dune::YaspGrid<2> > >, double, double, 1ul>, EngwHillenKnapp2014<MedicalDataManager<double, Dune::YaspGrid<2> >, Dune::YaspGrid<2> >, CFEM_L2OP<Dune::PDELab::QkLocalFiniteElementMap<Dune::GridView<Dune::DefaultLeafGridViewTraits<const Dune::YaspGrid<2> > >, double, double, 1ul> >, Dune::YaspGrid<2> >’
我认为尝试专门化我的用户代码将是一团糟。
实现可能不同签名的构造函数调用的正确方法是什么?
任何提示将不胜感激!
(ubuntu 16.04, gcc)