【发布时间】:2018-05-05 10:03:14
【问题描述】:
我想让 CRTP 基方法的返回类型取决于派生中成员的类型,例如:
template <typename C>
struct sum_a_b {
??? sum() { return static_cast<C*>(this)->a + static_cast<C*>(this)->b; }
}
template <typename T> struct a_b : sum_a_b<a_b<T>> { T a,b; };
我应该用什么代替???
我尝试了不同的方式来声明返回类型:
template <typename T>
struct base {
int get_ok() {
return static_cast<T*>(this)->value;
}
auto get_invalid() -> decltype(static_cast<T*>(this)->value) {
return static_cast<T*>(this)->value;
}
typename T::value_type get_incomplete_type_foo() {
return static_cast<T*>(this)->value;
}
auto get_incomplete_type_again() -> decltype(T().value) {
return static_cast<T*>(this)->value;
}
};
struct foo : base<foo> {
typedef int value_type;
value_type value;
};
编译的唯一方法是int get_ok,对于其他我得到的方法(get_invalid_cast):
invalid static_cast from type 'base<foo>*' to type 'foo*'
auto get_invalid() -> decltype(static_cast<T*>(this)->value) { return static_cast<T*>(this)->value; }
^
或(其他两个)
invalid use of incomplete type 'struct foo'
typename T::value_type get_incomplete_type_foo() { return static_cast<T*>(this)->value; }
^
【问题讨论】:
-
auto不起作用? -
@KillzoneKid afaik
auto没有尾随返回类型是> C++11 -
哦,我明白了,抱歉错过了标签细节
标签: c++ c++11 decltype crtp static-cast