C++ CRTP:如何推断要用作返回类型的成员类型?

C++ CRTP:如何推断要用作返回类型的成员类型?,c++,c++11,decltype,crtp,static-cast,C++,C++11,Decltype,Crtp,Static Cast,我想使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

我想使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; };
编译的唯一方法是
int-get\u-ok
,对于其他方法(对于
get\u-invalid\u-cast
):

从“base*”类型转换为“foo*”类型的静态\u转换无效
auto get_invalid()->decltype(static_cast(this)->value){return static_cast(this)->value;}
^
或者(另外两个)

对不完整类型“struct foo”的使用无效
typename T::value_type get_complete_type_foo(){return static_cast(this)->value;}
^

我认为c++14之前唯一可用的解决方法是使用类型特征:

#include <iostream>

template<typename T>
struct Value;

template <typename T>
struct Base
{
    typename Value<T>::type get_value(void)
    {  
        return static_cast<T*>(this)->m_value; 
    }
};

struct Derived;

template<> 
struct Value<Derived>
{
    using type = float;
};

struct Derived: public Base<Derived>
{
    Value<Derived>::type m_value{};
};

int main()
{
    Derived derived{};
    std::cout << derived.get_value() << std::endl;
}

auto
不起作用?@KillzoneKid afaik
auto
不带尾随的返回类型是>C++11哦,我知道了,很抱歉错过了标签说明如果派生的是模板,那是什么?我是否可以像第一个示例中那样,向前声明tempalte,然后专门化模板化的
派生的
值?
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; }
                            ^
#include <iostream>

template<typename T>
struct Value;

template <typename T>
struct Base
{
    typename Value<T>::type get_value(void)
    {  
        return static_cast<T*>(this)->m_value; 
    }
};

struct Derived;

template<> 
struct Value<Derived>
{
    using type = float;
};

struct Derived: public Base<Derived>
{
    Value<Derived>::type m_value{};
};

int main()
{
    Derived derived{};
    std::cout << derived.get_value() << std::endl;
}
template<typename U>
struct Derived;

template<typename U> 
struct Value<Derived<U>>
{
    using type = float;
};