当派生类使用基类构造函数时,推论似乎总是fail。然而,当基类有很多构造函数时,重新定义所有构造函数是非常笨拙的。当基类快速演变为新的构造函数时,这也是一个痛苦。老问题是两年多前提出的,所以我想知道:在 2020 年 c++17 和 c++2a 可用时,是否有任何解决办法?
template<typename ...As>
class base_t
{
public:
base_t(As... args){}
};
template<typename ...As>
class A_t: public base_t<As...>
{
public:
A_t(As... args): base_t<As...>{args...} {};
};
template<typename ...As>
class B_t: public base_t<As...>
{
using base_t<As...>::base_t;
};
int main()
{
base_t a{1, 2.0f};
A_t{1, 2.0f};
B_t{1, 2.0f}; //fails unless explicitly specialize the template
return 0;
}
根据@Sam 和@Barry 更新:
推导指南非常有帮助。然而,对于稍微复杂一点的情况,它仍然会失控:
template <typename A>
struct D_t {
A x;
D_t(A x) :x{x} {}
};
template<typename A, typename B>
class base2_t
{
public:
base2_t(A a, B b){std::cout << "1\n";}
base2_t(A a, D_t<B> c, int x){std::cout << "2\n";}
base2_t(A a, B b, int x){std::cout << "3\n";}
base2_t(A a, B b, int x, float y){std::cout << "4\n";}
explicit base2_t(A(*fp)(B)){std::cout << "5\n";}
// if we have lots of similar things like above
// we will quickly end up write lots of different
// guides.
};
template<typename A, typename B>
class C_t: public base2_t<A, B>
{
using base2_t<A, B>::base2_t;
};
template<typename A, typename B, typename ...As>
C_t(A, B, As...)->C_t<A, B>;
template<typename A, typename B>
C_t(A(*)(B))->C_t<A, B>;
float func1(int x)
{
return x;
}
int main()
{
C_t{1, 2.0f, 3};
base2_t{1, D_t{2.0f}, 3};
C_t{1, D_t{2.0f}, 3}; // this is wrong, we have to deal with it by checking types and write different guides.
base2_t{&func1};
C_t{&func1};
}
到 2023 年,proposal被接受于c++23 P2582R1但两者都没有gcc nor llvm已经实施了。但希望在今年年中这个问题最终能得到解决。