【发布时间】:2016-08-20 02:42:50
【问题描述】:
我有以下场景:
struct AP;
struct B
{
B() : m(2) {}
int m;
};
struct A : private B
{
A() : B(), n(1) {}
private:
int n;
friend AP;
};
struct AP
{
AP(A& a) : a_(a) {}
template<typename T>
struct A_B {
using type = typename std::enable_if< std::is_base_of< typename std::remove_reference<T>::type,
A >::value,
T >::type;
};
template<typename T>
operator typename A_B<T>::type()
{
return static_cast<T>(a_);
}
template<typename T>
typename A_B<T>::type get()
{
return static_cast<T>(a_);
}
int& n() { return a_.n; }
private:
A& a_;
};
int main()
{
A a;
AP ap(a);
ap.n() = 7;
const B& b = ap.get<const B&>();
//const B& b = ap; candidate template ignored: couldn't infer template argument 'T'
//auto b = static_cast<const B&>(ap); candidate template ignored: couldn't infer template argument 'T'
std::cout<<b.m;
}
注释行无法编译。 Clang++ 指出“候选模板被忽略:无法推断模板参数 'T'”
为什么我无法使用 cast 运算符获得对 A 基数的引用? 我认为这样代码看起来会更好。
【问题讨论】:
-
您的注释行尝试将
ap转换为B类型的引用,而ap的类型为AP,与B和A无关。您希望它如何工作? -
@wasthishelpful:我认为 OP 试图做的是将
AP实例的a_成员转换为B,这应该是有效的,因为A派生自@987654332 @.
标签: c++11 casting template-meta-programming