Sto*_*row 5 c++ templates class-names
有没有办法在编译时隐式引用类的名称?
具体来说,如果我想在的范围内声明template class Ausing 的实例,是否可以避免在声明该实例的语法中明确引用“ B” ?class Bclass Bclass A
为了更好地说明一个例子:
// main.cpp
#include <iostream>
using namespace std;
template <typename T>
class A
{
public:
typedef void (T::*TFunc)();
A( T& t ) : t_( t ) {}
void callFunc( TFunc tFunc ) { (t_.*tFunc)(); }
private:
T& t_;
};
class LongClassName
{
public:
LongClassName() : a_( *this ) {}
void pubFunc()
{
a_.callFunc( &LongClassName::privFunc ); // Can I avoid explicitly using "LongClassName" here?
}
private:
void privFunc() { cout << __PRETTY_FUNCTION__ << endl; }
A<LongClassName> a_; // Can I avoid explicitly using "LongClassName" here?
};
int main( int argc, char* argv[] )
{
LongClassName().pubFunc();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我尝试过的内容:
阅读C ++中是否有__CLASS__宏?,所以我知道没有__CLASS__(伪等效于__FUNCTION__)预处理器宏。该职位的一些解决方案从中提取类名__PRETTY_FUNCTION__-但这是不适用于这种情况的运行时解决方案。
我已经在StackOverflow上阅读了有关运行时间或编译时间的冲突 信息typeid(T);无论哪种方式,A<typeid(*this).name()> a_;都不会编译,并且无论如何都看起来是错误的:this在这种情况下,显然没有。
通过我的阅读,https: //en.cppreference.com/w/cpp/language/typeid上的文本清楚地表明这typeid是运行时,因此不适用于这种情况。
无法避免在LongClassName::privFunc和中使用类型名称A<LongClassName> a_;。
也就是说,您仍然可以使生活更轻松。您可以为其创建别名,LongClassName以便可以使用它的位置。新增中
using LCN = LongClassName;
Run Code Online (Sandbox Code Playgroud)
将让您LCN代替LongClassName