【发布时间】:2026-02-04 14:10:01
【问题描述】:
这个问题是针对 C++03,而不是 C++11。
我有一个案例,我正在使用具有多重继承的 CRTP,我很想知道是否有办法消除在下面指定 B 的类型时创建的冗余。
#include "boost/typeof/typeof.hpp"
#include "boost/units/detail/utility.hpp"
#include <iostream>
#include <string>
struct One{};
struct Two{};
template<typename T>
struct Type
{
static std::string name(void)
{
return boost::units::detail::demangle(typeid(T).name());
}
};
template<typename T1,
typename T2>
struct A
{
typedef A<T1, T2> Self;
A()
{
std::cout << Type<Self>::name() << std::endl;
}
};
template<typename T1,
typename T2,
typename T3>
struct B : public A<One, B<T1, T2, T3> >, // The B<T1, T2, T3> here is redundant
public A<Two, B<T1, T2, T3> >
{
typedef B<T1, T2, T3> Self;
B()
{
std::cout << Type<Self>::name() << std::endl;
}
};
int main(int argc, char* argv[])
{
B<int, int, int> t;
return 0;
}
在Coliru上看到这个
当B 的模板参数数量增加、模板参数本身很复杂以及B 从A 继承更多次时,问题会更加严重。我想尽量减少B 的模板参数的重复。具体来说,我正在寻找一种方法来访问B 的继承列表中的typedef B<T1, T2, T3> Self,或this 的一些等效编译时版本。
我不能:
- 使用前向声明为
B上方的B创建一个typedef,因为我无权访问模板参数 - 在继承定义中在中创建一个typedef,因为语法不允许这样做
- 从类内部访问 typedef,因为它还不存在
类似下面的东西(都不是无效代码,但显示我正在寻找的效果):
template<typename T1,
typename T2,
typename T3>
struct B : public A<One, Self>, // Cannot access the typedef yet
public A<Two, Self>
{
typedef B<T1, T2, T3> Self;
};
template<typename T1,
typename T2,
typename T3>
struct B : typedef B<T1, T2, T3> Self, // Invalid syntax
public A<One, Self>,
public A<Two, Self>
{
};
template<typename T1,
typename T2,
typename T3>
struct B : public A<One, B>, // I wish this would work
public A<Two, B>
{
};
template<typename T1,
typename T2,
typename T3>
struct B : public A<One, BOOST_TYPEOF(*this)>, // lol
public A<Two, BOOST_TYPEOF(*this)>
{
};
有没有办法访问this 的编译时版本?
【问题讨论】:
-
使用嵌套类型/元函数怎么样?
template<typename T1, typename T2, typename T3> struct M { struct B : A<One, B>, A<Two, B> {}; };由于缺少别名模板,在 C++03 中使用当然不如 C++03 好,但可以从中派生:template<typename T1, typename T2, typename T2> struct C : typename M<T1, T2, T3>::B {};
标签: c++ multiple-inheritance c++03 crtp