当派生类使用基类构造函数时,推导似乎总是失败。但是,当基类有很多构造函数时,重新定义所有构造函数是非常笨拙的。当基类用新的构造函数快速演化时,这也是一种痛苦。旧问题是在 2 年前提出的,所以我想知道:当 c++17 和 c++2a 可用时,2020 年是否有任何解决方法?
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;
}
Run Code Online (Sandbox Code Playgroud)
扣除指南非常有帮助。但是,对于稍微复杂一点的情况,它仍然会失控:
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};
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
144 次 |
| 最近记录: |